繁体   English   中英

简单的无限while循环-c

[英]Simple infinite while loop— c

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

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

"%i" // expects an integer

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

 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)=>才能从while循环中出来。

现在,如果您认为(gallonUsed = -1和milesDriven = -1)中的任何一个,则使用while(gallonsUsed!= -1 && milesDriven!= -1)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM