2016-11-15 31 views
1

我实现了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 


} 
+0

你在同一个控制流中有两个return语句吗? – mkmostafa

+0

它要返回maxValue和largestIndex ..你应该查找'struct'作为选项。 – solti

回答

0

所有的功能首先具有可达代码

template < typename T > 
int FindMax(T* array, int array_len) { 
      //... 

      return maxValue; 
      return largestIndex; 
      ^^^^^^^^^^^^^^^^^^^^^^ 
     } 
     //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; 
} 

您应该删除最后一个return语句。

至于错误,那么你应该写

int maxValue = FindMax(array, array_len); 
^^^^^^^^^^^^^ 
cout << maxValue << endl; // error here 

那就是你必须声明变量maxValue,并与算法的返回值赋给它。

+1

@LiamLaverty是的。主要名称maxValue是未知的,因为它没有被声明。 –

+0

@LiamLaverty算法中变量maxValue的范围受到算法主体的限制。这是它的局部变量,在算法之外是不可见的,并且不存在。 –

+0

为了打印出结果,哪种方法更好?在方法本身中有一个cout语句,所以你需要做的就是用参数调用main方法,或者在main方法中调用cout并给出方法返回的值的值maxValue? – Liam