0

我知道我应该自己调试这个......但相信我,我已经尝试过了,我很尴尬。我不明白为什么我的 while 循环是无限循环的。任何人都可以帮忙吗?

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

2 回答 2

4

乍一看,您似乎在使用浮点数据类型,而您应该使用整数。

"%i" // expects an integer

尝试使用int数据类型,或将格式更改为"%lf"

于 2013-09-18T01:12:45.893 回答
0
 while ( gallonsUsed != -1 || milesDriven != -1)

在这里,如果用户输入gallonsUsed = -1 和milesDriven = 2(比如说),那么

您的上述条件将是:while(0 || 1) ,相当于 while(1)。

同样,如果gallonUsed = 2(比如说)和milesDriven = -1,那么

您的上述条件将是:while(1 || 0) ,这再次等同于 while(1)。

当gallonUsed = -1 和milesDriven = -1 时

那么只有相当于 while(0) => 的 while(0||0) 才能退出 while 循环。

现在,如果您认为 (gallonUsed = -1 和 milesDriven = -1) 中的任何一个,在这种情况下,使用 while (gallonUsed != -1 && milesDriven != -1)

于 2017-01-30T12:51:45.647 回答