【问题标题】:Why wont this program run, but it will build?为什么这个程序不会运行,但它会构建?
【发布时间】: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


【解决方案1】:

此代码存在 三个 问题。 首先,正如@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] 处的值。

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

【讨论】:

  • Ahmm.. 关于int userNums[totVar] 的好点,我想我把它和一些 C# 混合在一起了。您应该在这里获得答案分数奖金。
  • 谢谢。这对我帮助很大。
【解决方案2】:

请参阅:@Pete Becker 以获得实际答案

在创建数组userNums之前需要初始化totVar

当你使用时

cin >> totVar;

稍后在您的软件中,您可能希望给它一个上限。

int userNums[1000];

并检查totVar 不超过 999。

【讨论】:

  • 谢谢,但是数组是否用 0 或其他什么填充了所有多余的数据?例如,假设我将 16 条数据放入数组中,是否会用 0 填充数组中的多余空间?
  • @PeteMcGreete 不,不会。如果你想初始化你的数组,你可能想写int userNums[1000] = {};
猜你喜欢
  • 1970-01-01
  • 2022-12-29
  • 2019-02-08
  • 1970-01-01
  • 2014-01-08
  • 1970-01-01
  • 2021-12-26
  • 2020-12-28
  • 1970-01-01
相关资源
最近更新 更多