Reputation: 35
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;
}
Upvotes: 0
Views: 453
Reputation: 182
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)
Upvotes: 0
Reputation: 4357
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"
Upvotes: 4