简体   繁体   中英

Simple infinite while loop— c

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;    
}

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"

 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)

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