0

I know I should debug this myself... but believe me I've tried and I'm VERY embarrassed. I can't understand why my while loop is infinitely looping. Can anyone help?

#include <stdio.h>

int main ( void )
{
    double milesDriven;
    double gallonsUsed;
    double totalMilesDriven;
    double totalGallonsUsed;
    float milesPerGallon;
    float totalMpG;

printf( "%s", " Enter the gallons used (-1 to end): " );
scanf( "%i", &gallonsUsed);

printf( " Enter the miles driven: " );
scanf( "%i", &milesDriven);


while ( gallonsUsed != -1 || milesDriven != -1)
{
     totalGallonsUsed += gallonsUsed;
     totalMilesDriven += milesDriven;

     milesPerGallon = ( milesDriven / gallonsUsed );
     printf( " The miles/gallon for this tank was %f\n", milesPerGallon );

     printf( "%s", " Enter the gallons used (-1 to end): " );
     scanf( "%i", &gallonsUsed);

     printf( " Enter the miles driven: " );
     scanf( "%i", &milesDriven);

}


totalMpG = ( totalMilesDriven / totalGallonsUsed );
printf( " The overall average miles/gallon was %.6f\n ", totalMpG); 
return 0;    
}
2
  • 1
    Maybe you want that || to be && ? Sep 18, 2013 at 1:12
  • 1
    Also, the scan("%i") argument is a double. Not an int. Maybe you wanted scanf("%lf", ...) Sep 18, 2013 at 1:13

2 Answers 2

4

At first glance, it seems to be that you're using floating point datatypes, when you should be using integers.

"%i" // expects an integer

Try using the int datatype, or change your formatting to "%lf"

3
  • 1
    -1 is one of those values that can be represented exactly so, while your warning to be careful is apt, it's not relevant in this specific case. However, +1 since you almost certainly nailed the problem.
    – paxdiablo
    Sep 18, 2013 at 1:16
  • 1
    @paxdiablo yeah I didn't check, honestly. I'll edit my answer
    – tay10r
    Sep 18, 2013 at 1:17
  • Thanks! I'll admit, I'm new to C so I didn't know about the %lf for double!
    – TommyD
    Sep 18, 2013 at 1:43
0
 while ( gallonsUsed != -1 || milesDriven != -1)

Here if user will enter gallonsUsed = -1 and milesDriven = 2(say), then

your above condition will be: while(0 || 1) , which is equivalent to while(1).

Similarly if gallonUsed = 2(say) and milesDriven = -1, then

your above condition will be: while(1 || 0) , which is again equivalent to while(1).

When both gallonUsed = -1 and milesDriven = -1

then only while(0||0) equivalent to while(0) => will be able to come out of the while loop.

Now if you wnat that if any one of (gallonUsed = -1 and milesDriven = -1), in that case, use while ( gallonsUsed != -1 && milesDriven != -1)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.