我完成了我的递归反向(数组)C ++程序,然而,它输出部分正确,额外的“10”,我相信是因为我的const int SIZE = 10.我不确定我在哪里犯了错误(s )在我的程序中,并希望对错误发生的位置提出一些建议。谢谢。任何帮助将不胜感激。这是我收到的输出:
Original Array: 9 2 6 11 0 18 4 13 2 7
Reversed Array: 7 2 13 4 18 0327053270532705 10
以下是我的代码:
#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <ctime>
const int SIZE = 10;
unsigned int seed = int (time(0));
using namespace std;
double random(unsigned int &seed);
void initialize(int a[]);
void print_array(int a[]);
void recursive_reverse_array(int a[], int[], int[]);
double random(unsigned int &seed)
{
const int MODULUS = 15749;
const int MULTIPLIER = 69069;
const int INCREMENT = 1;
seed = ((MULTIPLIER *seed) + INCREMENT) % MODULUS;
return double (seed)/double(MODULUS);
}
void initialize(int a[])
{
for (int i = 0; i < SIZE; ++i)
a[i] = (20 * (random(seed)));
}
void print_array (int a[])
{
for (int i = 0; i < SIZE; ++i)
cout << setw(4) << a[i];
cout << endl;
}
void recursive_reverse_array(int a[],int num1, int num2)
{
int k;
if(num1 < num2)
{
a[num1] = a[num2];
a[num2] = k;
recursive_reverse_array(a, num1 + 1, num2 - 1);
}
}
int main ()
{
int arr[SIZE];
cout << "Original Array:";
initialize(arr);
print_array(arr);
recursive_reverse_array(arr, 0, SIZE - 1);
cout << "Reversed Array:";
print_array(arr);
return 0;
}
答案 0 :(得分:1)
在int k = a[num1];
功能中设置recursive_reverse_array
,这应该有效。目前,你没有初始化,我认为这会给你部分正确的输出。
答案 1 :(得分:1)
你在代码中犯了一个愚蠢的错误。请参阅以下代码并用它替换您的代码。
#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <ctime>
const int SIZE = 10;
unsigned int seed = int (time(0));
using namespace std;
double random(unsigned int &seed);
void initialize(int a[]);
void print_array(int a[]);
void recursive_reverse_array(int a[], int[], int[]);
double random(unsigned int &seed)
{
const int MODULUS = 15749;
const int MULTIPLIER = 69069;
const int INCREMENT = 1;
seed = ((MULTIPLIER *seed) + INCREMENT) % MODULUS;
return double (seed)/double(MODULUS);
}
void initialize(int a[])
{
for (int i = 0; i < SIZE; ++i)
a[i] = (20 * (random(seed)));
}
void print_array (int a[])
{
for (int i = 0; i < SIZE; ++i)
cout << setw(4) << a[i];
cout << endl;
}
void recursive_reverse_array(int a[],int num1, int num2)
{
int k;
if(num1 < num2)
{
k=a[num1];
a[num1] = a[num2];
a[num2] = k;
recursive_reverse_array(a, num1 + 1, num2 - 1);
}
}
int main ()
{
int arr[SIZE];
cout << "Original Array:";
initialize(arr);
print_array(arr);
recursive_reverse_array(arr, 0, SIZE - 1);
cout << "Reversed Array:";
print_array(arr);
return 0;
}
您必须在代码中使用k = a[num1];
。希望它能奏效。