如何在获得收入和费用之和时使用多个for循环C ++?

时间:2014-05-31 02:04:21

标签: c++

我是C ++的新手,我正在学习for循环。

这是作业问题:

  

MyStore的销售经理想要一个程序,允许她输入公司的收入和支出金额,这些金额总是整数。每次运行程序时,收入和费用金额可能会有所不同。例如,销售经理可能需要输入五个收入金额和三个费用金额。或者,她可能需要输入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;

1 个答案:

答案 0 :(得分:1)

将sumIncome和sumExpense初始化为零

int sumIncome=0;
int sumExpense=0;
int profitorloss=0;

如果你没有初始化任何变量并在arithmetice操作中使用,那么一些垃圾值会起作用,这可能是原因

if(sumExpense>sumIncome)
{
    cout<<"total loss"<<sumExpense-sumIncome;
}
else
{
    cout<<"total profit"<<sumIncome-sumExpense;
}