我如何使用多个循环c++,同时获得收入和费用的总和

How do I use multiple for loops C++ while obtaining the sum of income and expense?

本文关键字:何使用 循环 c++      更新时间:2023-10-16

我是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;
}