循环无限地运行,不管输入的整数是多少
Loop runs ad infinitum, regardless of int entered
自从我发布这篇文章后,我休息了一段时间,并阅读了我正在学习的 C 编程书籍的一半(哈佛 cs50 书)。我现在应该能够解决这个问题,但我做不到。
无论输入什么整数,程序都在连续循环运行;无限打印 "Good for you..."。
示例代码:
//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 看起来像这样。
while(prefer <= 10 && prefer > 0);
自从我发布这篇文章后,我休息了一段时间,并阅读了我正在学习的 C 编程书籍的一半(哈佛 cs50 书)。我现在应该能够解决这个问题,但我做不到。
无论输入什么整数,程序都在连续循环运行;无限打印 "Good for you..."。
示例代码:
//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 看起来像这样。
while(prefer <= 10 && prefer > 0);