2017-01-15 54 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

相关问题