我如何使用多个循环c++,同时获得收入和费用的总和
How do I use multiple for loops C++ while obtaining the sum of income and expense?
我是c++新手,正在学习for循环。
这是作业问题:
MyStore的销售经理想要一个程序,允许她输入公司的收入和支出金额,这些金额总是整数。每次程序运行时,收入和费用金额的数量可能会有所不同。例如,销售经理可能需要输入5个收入金额和3个费用金额。或者,她可能需要输入20个收入金额和30个费用金额。该程序应计算并显示公司的总收入、总费用和利润(或亏损)。
我试图使用两个for循环来获得费用和收入的总和,但是我在第二个循环中一直得到错误的总和。我不确定我是应该使用多个循环还是一起做一些不同的事情。谢谢你的帮助。谢谢!
这是我目前得到的部分内容:
if (incNum > 0)
{
// Get the income items and calculate the sum total.
for (int count = 1; count <= incNum; count++)
{
cout << "Enter the income items: " << count << ": ";
cin >> income;
sumIncome += income; // Calculate the sum total.
}
}
// Display the total income.
cout << fixed << showpoint << setprecision(2);
cout << "The total sum of income is $" << sumIncome << endl;
cout << "income=" << income << endl;
// Get the number of items for income.
cout << "How many items do you have to enter for expenses?";
cin >> expNum;
if (expNum > 0)
{
// Get the expense items and calculate the sum total.
for (int count = 1; count <= expNum; count++)
{
cout << "Enter the expense items" << count << ":";
cin >> expense;
sumExpense += expense; // Calculate the sum total.
}
}
// Display the total income.
cout << fixed << showpoint << setprecision(2);
cout << "The total expense items are $" << sumExpense << endl;
将sumIncome和sumExpense初始化为0
int sumIncome=0;
int sumExpense=0;
int profitorloss=0;
如果你没有初始化任何变量并且在算术运算中使用一些垃圾值这可能是原因
if(sumExpense>sumIncome)
{
cout<<"total loss"<<sumExpense-sumIncome;
}
else
{
cout<<"total profit"<<sumIncome-sumExpense;
}
相关文章:
- 使用循环创建类对象
- 为什么在递归中使用循环会产生意想不到的结果?
- 使用循环将多行写入.txt
- 如何编译使用循环引用的代码?
- 如何使用循环逐个读取C++中的多个文件
- 如何使用循环结束 c++ 上的行
- 如何使用循环对所有数字求和?
- 修改向量中的字符串?(不使用循环)
- 在C++中使用循环创建多个对象
- 如何向用户显示特定错误,要求他/她使用循环再次提供输入?
- 如何使用循环编写此递归
- 递归回溯打印长度为N的二进制数的所有组合,而不使用循环
- 阶乘使用循环递增给出垃圾值
- 在磁盘上使用循环缓冲区
- 使用循环声明 Mat 类
- 使用循环进行词典字符串比较
- 练习循环和使用循环 1 次以及如何获取数组的最大值
- 如何在不使用循环的情况下回到代码的顶部?
- 无需使用循环,就将ISBN-10的前9位数字读取为字符串并计算第10位数字
- 如何使用循环从另一个字符串创建一个没有空格的新字符串