我被分配了一个用C编写的程序,让用户输入将向鱼缸中添加多少额外的水,24小时后鱼将被"烧烤"。我遇到的问题是如果我在scanf中输入比10大的数。循环重复并永远给出相同的输出。我使用正确的位置持有人扫描?
#include <stdio.h>
int main(void) {
//Declares variables
double fishTank = 500;
int hours = 0;
int addWater;
//asks user for input.
printf("Please enter additional water to be added per hour:");
scanf("%d", &addWater);
//while fishtank is greater then or equal to 100 it will run this loop
while (fishTank >= 100) {
fishTank = fishTank - (fishTank * .1) + addWater;
printf("The tank still has %f gallons remainingn", fishTank);
//increments hours by 1
hours = hours + 1;
}
//if hours drops below 24 it will print this output
if (hours < 24) {
printf("Out of water at hour %d when remaining gallons were %fn", hours, fishTank);
}
//if hours is greater then 24 by the time the loop ends it will print this.
else if (hours >= 24) {
printf("Get out the BBQ and lets eat fish.n");
}
system("pause");
return 0;
}
看这个等式
fishTank = fishTank - (fishTank * .1) + addWater;
如果开始fishTank
= > 100
,当addWater
>= 10时,(fishTank * .1)
不能减小fishTank
,因为经过几次迭代后,fishTank * 0.1
等于addWater
。
while
的条件更改为
while (hours <= 24 && fishTank >= 100)
水箱每小时损失其当前容量的10%,如果它有100个单位就是10个单位。无论用户输入什么,它都会获得收益。如果这个数字大于10,每次它可能低于100,它就会获得足够的收益,再次超过100。即使它正好回到100,增加10或更多也足以使它保持在那里-所以它永远循环
你的while语句需要是:
while (fishTank >= 100 && hours < 24) {