2014-09-26 106 views
-5

我試圖找到平均值,它適用於我輸入的第一組數字,但第二組稍微偏離了,我假設這是因爲我沒有重置數組正確或我錯過重置其中的一個值。C++重置數組爲null

#include <iostream> 
#include <cmath> 
using namespace std; 


int main() { 

    int array [15]; 
    int amount, step, length; 
    double total; 
    step = -1; 
    amount = 0; 
    length = 0; 
    total = 0; 

    cin >> amount; 

    for(int count = 0; count!=amount; count++){ 

     while (array[step] != 0){ 
      step++; 
      cin >> array[step]; 
     } 
     length = step; 

     while (step >= 0){ 
      total = total + array[step]; 
      array[step] = 0; 
      step--; 
     } 
     total = total/length; 
     cout << round(total) << " "; 
     step = -1; 

    } 


    return 0; 

} 

回答

4
step = -1; 

的代碼

while (array[step] != 0){ 

首先過程產生未定義的行爲。數組的第一個條目應該索引爲0.