2017-01-15 100 views
1

我一直在試圖在代碼塊中運行這個平均的計算器程序,它的構建沒有錯誤,但它不能運行的原因,我不知道爲什麼。 我的代碼如下爲什麼不會這個程序運行,但它會建立?

#include <iostream> 

    using namespace std; 

double getAverage(int amount, int numbers[]) { 
    // Declare the variables 
    int total = 0; 
    double avg = 0; 
    //Find each number in the array then add it to the total 
    for (int i = amount; i > 0; i--) { 
    total += numbers[i]; 

    } 
    //Divide the total by the amount to get the average 
    avg = total/amount; 
    cout << "The Average is: "; 
    //Return the average 
    return avg; 
} 

int main() { 
    // Declare the variables and arrays 
    int varNum = 1; 
    int totVar; 
    int userNums[totVar]; 
    //Ask user for how many variables they want then record it 
    cout << "How many variables would you like to have? "; 
    cin >> totVar; 
    //Ask the user for each variable, then record it into the array 
    for (int i = totVar; i > 0; i--) { 
    cout << "Please input variable " + varNum; 
    cin >> userNums[i]; 
    varNum++; 

    } 
    return 0; 
} 
+2

在創建數組'userNums'之前初始化'totVar'。 – Stefan

+0

它不適合我。 –

+4

將userNums聲明爲std :: vector可以解決許多問題。 – stefaanv

回答

1

有問題與此代碼。 第一個,正如@stefan所說的,totVar在用作數組大小時尚未初始化。但是,這並不重要,因爲int userNums[totVar];是不合法的C++(由於GCC擴展而編譯)。而第三,這些循環

for (int i = totVar; i > 0; i--) { 
    cout << "Please input variable " + varNum; 
    cin >> userNums[i]; 
    varNum++; 
} 

for (int i = amount; i > 0; i--) { 
    total += numbers[i]; 
} 

通無效索引到陣列。大小爲N的數組具有從0到N-1的有效索引。通過該第一個循環的第一個通道訪問numbers[totVar],該數組離開數組的末尾。寫這樣的第一個循環的常用方法是

for (int i = 0; i < totVar; ++i) 
    cin >> userNums[i]; 

這在numbers[0]numbers[1],... numbers[totVar-1]訪問值。

對第二個循環做同樣的事情。

+0

Ahmm ..關於'int userNums [totVar]'的好處,我想我正在將它與一些C#混合。這裏你應該得到答案 - 分數獎金。 – Stefan

+0

謝謝。這確實幫了我很多。 – PeteMcGreete

1

見:@Pete貝克爾的實際答案

您需要在創建數組userNums

之前初始化totVar當您使用

後來在你的軟件中,你可能想給它一個upp呃約束。

int userNums[1000]; 

並檢查totVar沒有長度不可超過999

+0

謝謝,但數組是用0填充所有多餘的數據還是其他?例如,假設我將16個數據放在數組中,是否用0填充數組中的多餘空間? – PeteMcGreete

+0

@PeteMcGreete不,它不會。如果你想初始化你的數組,你可能想寫'int userNums [1000] = {};' –

+0

好的,謝謝。這有很大幫助。 – PeteMcGreete

相關問題