Cpp代码故障(显示意外数字)
Cpp Code Malfunctioning (showing unexpected numbers)
这是我为计算平均分数而编写的程序:
#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。
感谢所有的评论!
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 检查输入是否不是整数或数字
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 如何用数字处理log(0)
- 最高有效数字侧的第N位
- 在C++中对T*类型执行std::move的意外行为
- 如何获取一个数字的前3位
- 查找最接近的大于当前数字的数字的索引
- 找到两对数字,使它们的乘积的绝对差最小化
- 我想做一个彼此不同但重复出现的数字
- 将数字转换为字母(例如:123 转换为一二三)
- Cpp代码故障(显示意外数字)
- Spirit X3:自定义数字解析器在结果中产生意外的前导零
- 递归函数用于计算 n 个数字之和的意外输出
- 找到printf的意外错误,该格式为0.1F,用于四舍五入数字
- 意外参数通过使用STL数字的顺序
- C :Bool方法在COUT语句之后返回意外数字
- 双精度数字程序意外值
- C++ 意外的数字输出