简体   繁体   中英

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

I'm uber new to C++ and am learning about for loops.

This is the homework problem:

The sales manager at MyStore wants a program that allows her to enter the company's income and expense amounts, which always will be integers. The number of income and expense amounts may vary each time the program is run. For example, the sales manager may need to enter five income amounts and three expense amounts. Or, she may need to enter 20 income amounts and 30 expense amounts. The program should calculate and display the company's total income, total expenses, and profit (or loss).

I was trying to use two for loops to get the sum of the expense and the income but I keep getting the wrong sum for the second loop. I'm not sure if I should use multiple loops or do something different all together. I appreciate any help. Thanks!

Here is part of what I've got so far:

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;

Initialise your sumIncome and sumExpense to zero

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

If you don't initialize any variable and used in arithmetice operation some garbage value come into play so that might be the cause

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM