0

I'm given some variable values which I read from a file and I perform a running total calculation. My goal is to find out how many total calculations I've done. I can get the number right by subtracting 1 from my counter at the end but I would like to not have to do that by changing my condition to better suit it. I realize I'm not using counter in my condition, is that a problem?

Input example: a=10, b=5, t=70

Any help would be appreciated. Tried changing the condition to sum < t instead but it seems to over-calculate past 70.

//Reads and calculates a, b and t, and outputs number of dishes to output.txt
while (inFile >> a)
{       
inFile >> b >> t;

for (counter = 0; sum <= t ; counter++)
{
sum += a + (counter * b);
}
outFile << " " << a << "\t\t" << b << "\t\t" << t << "\t\t" << counter -1 << endl; //Output iteration results

//Reset total before next iteration
sum = 0;
}
Cornel
  • 180
  • 2
  • 4
  • 13
  • 1
    if your counter is t why are you comparing with sum instead of counter – Hariom Singh Feb 09 '19 at 09:55
  • 1
    Surely `for (counter = 0; counter < t ; counter++)`? But maybe not, you haven't explained what you are trying to do very well. – john Feb 09 '19 at 09:57
  • T is actually another variable that I have to compare my sum to, to make sure I don't go above its value. Would a while loop be better in this case? – Cornel Feb 09 '19 at 09:59
  • 1
    @Cornel Well that's your problem. You should test **before** `sum` goes over `t` not afterwards. Because you are testing afterwards you do one too many calculations and your final value of `sum` will be too large. `for (counter = 0; sum + a + (counter * b) <= t ; counter++)`. You could probably simplify that. – john Feb 09 '19 at 10:00

1 Answers1

1

Something like this. It uses a temp variable which is the next value of sum and aborts the loop if that value is too large.

for (counter = 0; ; ++counter)
{
    int temp = sum + a + (counter * b);
    if (temp > t)
        break; // too big quit the loop
    sum = temp;
}

Now counter and sum should have the correct values at the end of your loop.

john
  • 85,011
  • 4
  • 57
  • 81
  • Thank you, John and everyone else. That was my issue and now I understand. One way would be to check the sum before summing. I like the temp method too. – Cornel Feb 09 '19 at 10:08