Infinite Loop Help!
Jun 27, 2013 at 1:44am UTC
Hi. I don't know why why program doesn't work the way I want to.It keeps looking whenever I want to type '-1'. I know I', experiencing an infinite loop but I'm not sure how to fix it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
// exercise 3
#include <iostream>
using namespace std;
int main()
{
double miles;
double gallous;
double T1miles;
T1miles = 0;
double Tgallous;
Tgallous = 0;
double T2miles;
double MPG;
double counter;
counter = 0;
while (counter >= 0)
{
cout << "Enter miles driven(-1 to quit): " << endl;cin>>miles;
cout<<"Enter gallons used: " <<endl;cin>>gallous;
MPG = miles/gallous;
cout << "MPG this trip: " <<MPG<<endl;
T1miles = T1miles + miles;
Tgallous = Tgallous + gallous;
T2miles = T1miles/Tgallous;
cout<<"Total MPG: " <<T2miles;
cout<<endl;
counter = counter + 1;}
}
Jun 27, 2013 at 1:46am UTC
Erase lines from your code until you isolate the issue
Jun 27, 2013 at 1:50am UTC
sorry i don't really understand what you mean, example?
Jun 27, 2013 at 2:15am UTC
You haven't set the condition for the program to quit when you input -1.
Jun 27, 2013 at 3:28am UTC
When do you want it to allow "-1" to be the option to quit? Only for when they're entering the miles?
I think this will work:
1 2 3 4
if (miles==-1)
{
break ;
}
If you put that after
cin>>miles;
, I believe it will work.
Jun 27, 2013 at 8:00pm UTC
the counter shouldn't be the condition
miles is the condition
you aren't even inputting into the counter
Jun 27, 2013 at 8:03pm UTC
and it doesn't test the condition again until the end of the loop
Jun 27, 2013 at 8:04pm UTC
while (miles != -1 )
Topic archived. No new replies allowed.