自从我发布这篇文章并通读了我正在学习的 C 编程书(哈佛 cs50 书(的一半后,我已经休息了一段时间。我现在应该可以解决这个问题,但不能。
无论输入什么整数,程序都在连续循环中运行;打印"对你有好处..."无穷无尽。
示例代码:
//example 3 version2 from chapter 11, beginner programming in c
#include <cs50.h>
#include <stdio.h>
int main ()
{
int prefer;
printf("On a scale from 1 to 10, how happy are you?n");
scanf(" %d", &prefer);
while(prefer >= 1 || prefer <= 10)
//goal is for program to run while entered int "prefer" is between 1 - 10
if (prefer > 10)
{
printf("Oh really, now? Can't follow simple directions, can you?n");
printf("want to try that again? 1 through 10...?n");
scanf(" %d", &prefer);
}
else if (prefer >= 8)
{
printf("Good for you!n");
}
else if (prefer <= 5)
{
printf("Cheer up : )n");
}
else if (prefer <= 3)
{
printf("Cheer up, Buttercup!n");
}
else
{
printf("Get in the RIVER with that attitude!n");
}
return 0;
}
运算符<
和&&
是二元运算符。当我们使用它们时,它会比较左侧和右侧值。上面的同时看起来像这样。
while(prefer <= 10 && prefer > 0);