我實現了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