简单的无限循环 - c

时间:2013-09-18 01:08:45

标签: c while-loop infinite-loop

我知道我应该自己调试一下......但是相信我,我已经尝试过了,我非常尴尬。我无法理解为什么我的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;    
}

2 个答案:

答案 0 :(得分:4)

乍一看,当你应该使用整数时,似乎是你正在使用浮点数据类型。

"%i" // expects an integer

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

答案 1 :(得分: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 || 0)等于while(0)=&gt;将能够走出while循环。

现在,如果你知道(gallonUsed = -1和milesDriven = -1)中的任何一个,那么使用while(加仑使用!= -1&amp;&amp; milesDriven!= -1)