Cpp代码故障(显示意外数字)

时间:2018-07-17 12:54:15

标签: c++

这是我编写的用于计算平均分数的程序:

#include <iostream>

int main() {

std::cout << "Welcome to the average marks calculator! Enter your marks below separating them with a space: " << std::endl;

//uses cnt to calculate the number of points entered
int val,sum,cnt = 0;

for (; std::cin >> val; cnt++) {

    sum += val;

}

sum /= cnt;

std::cout << "Your average marks are " << sum << " points." << std::endl;

return 0;

}

当我运行它时,它的内容如下:

  

欢迎来到平均分计算器!在您的标记下方输入>,并用空格隔开:

     

70 80 90 80 70 80 80

     

您的平均分数是85198117点。

显然不希望有整数85198117。我确定这是这里代码的问题。

您的任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:0)

FIX:

#include <iostream>

int main() {

std::cout << "Welcome to the average marks calculator! Enter your marks below separating them with a space: " << std::endl;

//uses cnt to calculate the number of points entered
int val,sum = 0,cnt = 0;

for (; std::cin >> val; cnt++) {

    sum += val;

}

sum /= cnt;

std::cout << "Your average marks are " << sum << " points." << std::endl;

return 0;

}
  

int val,sum = 0,cnt = 0;

总和必须用0(或其他任何数字)初始化,以避免未定义。

感谢所有评论!