C++For循环.Int.值的求和不正确
C++ For Loop. Int. values are not being summed correctly
这里是初学者。所以我试图让这个代码打印出每年的总价值。我为每个值输入了10,第三年它会返回126,而我预计会返回120。其他两年将返回正确的值120。我很难弄清楚为什么这没有按预期工作。
#include <iostream>
int main()
{
using namespace std;
const int Years = 3;
const int Months = 12;
int booksales[Years][Months];
int total[3];
for (int year = 0; year < Years; ++year)
{
int yr_total = 0;
for (int month = 0; month < Months; ++month)
{
cout << "Enter book sales for year " << (year + 1)
<< " month " << (month + 1) << ": ";
cin >> booksales[year][month];
total[year] += booksales[year][month];
}
}
cout << "TOTAL for year 1: " << total[0] << endl;
cout << "TOTAL for year 2: " << total[1] << endl;
cout << "TOTAL for year 3: " << total[2] << endl;
cout << "OVERALL TOTAL: " << total[0] + total[1] + total[2] << endl;
return 0;
}
您没有初始化数组
int total[3];
因此,在本声明中,
total[year] += booksales[year][month];
行为是未定义的。
写入
int total[3] = {};
此外,此声明在外循环内
int yr_total = 0;
是多余的。未使用变量。
C++不会将变量初始化为已知值。在这种情况下,您将年度总数相加为一个未初始化数据数组(total
)。令人惊讶的是,第一年和第二年没有出现类似的问题。
看起来您试图使用变量yr_total
而不是数组总数来清除此数据。尝试用以下内容替换年份循环的第一行:total[year] = 0;
代码的主要问题是初始化部分。
理想情况下,应该初始化总数组,而不是将其保留为垃圾值。
int total[3] = {};
希望能有所帮助。
相关文章:
- 使用2个键的cpp-stl::优先级队列排序不正确
- 正弦级数方程计算不正确
- 我试图制作一个程序,要求用户输入问题和答案,但程序循环不正确
- 密码登录程序将永远循环并显示不正确的结果
- 在C++中返回不正确的楼层函数值
- 形状对象的旋转和缩放不正确C++
- C++ 读取文件读取文件不正确
- 关于类的 Python 文档 - 对C++的引用不正确
- 特征 LLT 模块给出不正确的结果?
- glibcxx STL 在实现 std::valarray::sum() 时是否不正确?
- 如果语句逻辑不正确
- 来自逆 vp 矩阵和相机位置的光线方向不正确
- 不正确的操作数类型 MSVC
- 数组填充了不正确的值
- 我是否不正确地集中了这些字符数组?
- 为什么除非我使用 cout,否则我的值不正确?
- 调用求和或获取乘积的函数不正确
- 如果通过循环求和,下面的程序会找到正确的答案,但如果通过GP的公式求和,则会找到不正确的答案.为什么
- C++For循环.Int.值的求和不正确
- 返回不正确值的数组的顺序求和