我在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 remaining\n", 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 %f\n", 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;
}
答案 0 :(得分:1)
看看等式
fishTank = fishTank - (fishTank * .1) + addWater;
如果开头fishTank
为> 100
,(fishTank * .1)
如果fishTank
&gt; = 10则无法减少addWater
,因为经过一些迭代{{1} }变得等于fishTank * 0.1
。
我想,你的解决方案是正确的,但你应该提供一种替代方法。例如,将addWater
的条件更改为
while
答案 1 :(得分:0)
坦克每小时失去其当前音量的10%,如果它有100个单位则为10个单位。它会获得用户输入的任何内容。如果这个数字大于10,那么每次它都可以降到100以下,它就会再次超过100。即使它回到正好100,添加10或更多也足以让它保持在那里 - 所以它永远循环
你的while语句必须是:
while (fishTank >= 100 && hours < 24) {