[英]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.