2016-11-15 33 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