我实现了findMax方法&测试人员测试此函数。之前,我将findMax方法设置为void,并且在方法结束时只是简单地使用了最大值< < <,以便在主测试器中调用它时,它会打印出我想要的结果。从Find Max方法返回一个int值并在测试文件中打印
我想改变,所以方法的返回类型是int,并在主要能够打印出方法返回的值。当我尝试在测试程序文件中操作变量maxValue时,它表示变量未定义。
我该如何解决这个问题?还有什么是最合适的方式来做到这一点?将该方法作为void类型并在方法中具有cout语句或将其作为整数类型使其在最后返回int?
谢谢。
#ifndef FINDMAX_H
#define FINDMAX_H
#include <iostream>
using namespace std;
template < typename T >
int FindMax(T* array, int array_len) {
if (!array || array_len <=0) {
cout << "Invalid Array" << endl;
exit(1);
}
//T * newArray = new int[array_len]; //create new array
T maxValue = array[0]; //set to the first array element
int largestIndex = 0;
for (int i = 1; i < array_len; i++) { //going through array from pos 2
if (array[i] > maxValue) { //checking if value at array position i is > maxValue
maxValue = array[i]; //set maxValue = to element at current Array position
largestIndex = i; //set largest index = to the current index it is at
}
return maxValue;
}
//cout << "The max value in this array is: " << maxValue << endl;//return highest value in array
//cout << "The max value is at position : " << largestIndex << endl;//return position of highest value in the array
//cout << "" << endl;
}
#endif
仪
#include "FindMax.h"
#include <iostream>
using namespace std;
#include <string>
int main() {
int array_len = 10;
int* array = new int[array_len];
double* array2 = new double[array_len];
for (int i = 0; i < array_len; i++) //fill array 1
array[i] = i * i;
for (int i = 0; i < array_len; i++) //fill array 2
array2[i] = i * 2.5;
FindMax(array, array_len);
cout << maxValue << endl; // error here
}
你在同一个控制流中有两个return语句吗? – mkmostafa
它要返回maxValue和largestIndex ..你应该查找'struct'作为选项。 – solti