gpt4 book ai didi

c++ - 为什么这个程序不会运行,但它会构建?

转载 作者:行者123 更新时间:2023-11-30 03:34:54 25 4
gpt4 key购买 nike

我一直在尝试在代码块中运行这个普通的计算器程序,它构建时没有错误,但由于某种原因它无法运行,我不知道为什么。我的代码在下面

#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;
}

最佳答案

此代码存在三个问题。 首先,正如@stefan所说,totVar在作为数组大小的时候还没有初始化。但这并不重要,因为 secondint 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] 的值。

对第二个循环做同样的事情。

关于c++ - 为什么这个程序不会运行,但它会构建?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41665493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com