我编写了一个程序,使用分治法来计算数组的最大值,但输出为0。
#include <iostream>
using namespace std;
int array[50];
void maximum(int index1, int index2, int&max_number) {
int max_number1;
int max_number2;
int half;
if (index1 == index2)
max_number = array[index1];
else {
half = (index1 + index2) / 2;
maximum(index1, half, max_number1);
maximum(half + 1, index2, max_number2);
if(max_number1 < max_number2)
max_number = max_number2;
else
max_number = max_number1;
}
}
int main() {
int index1;
int index2;
int max_number = 0;
cout << "index2 = ";
cin >> index2;
for (index1 = 0; index1 < index2; index1++)
cin >> array[index1];
maximum(index1, index2, max_number);
cout << "maximum number = " << max_number;
return 0;
}
我该怎么办?
最佳答案
您在这部分代码中有错字
for(index1 = 0; index1 < index2; index1++)
index1将增加到index2,然后
maximum(index1, index2, max_number);
会在1st / 2nd参数中传递相同的值,您可以像这样更改代码
for(index1 = 0; index1 < index2; index1++)
cin>>array[index1];
index1 = 0;
maximum(index1, index2, max_number);
关于c++ - 通过分治法计算数组的最大数目,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49095787/