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

Cpp Code Malfunctioning (showing unexpected numbers)

本文关键字:意外 数字 显示 代码 故障 Cpp      更新时间:2023-10-16

这是我为计算平均分数而编写的程序:

#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。我确信这里的代码有问题。

如有任何帮助,我们将不胜感激。谢谢

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;

sum必须由0(或任何其他数字(初始化,以避免UNDEFINED。

感谢所有的评论!