【发布时间】:2017-01-16 05:08:48
【问题描述】:
我一直试图在代码块中运行这个普通的计算器程序,它构建时没有错误,但由于某种原因它无法运行,我不知道为什么。 我的代码如下
#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;
}
【问题讨论】:
-
在创建数组
userNums之前初始化totVar。 -
它不适合我。
-
将 userNums 声明为 std::vector 可以解决很多问题。
-
出于某种原因它为我构建。
-
int userNums[totVar];-- 这不是合法的 C++,因为数组不能使用变量作为项目数来声明。此代码将无法使用符合 ANSI 的 C++ 编译器 (example here) 进行编译,并且使用以下命令行参数将无法编译(您可能正在使用g++):-Wall -pedantic。
标签: c++ codeblocks