【问题标题】:Loop runs ad infinitum, regardless of int entered循环无限运行,无论输入的 int 是多少
【发布时间】:2019-03-15 23:26:01
【问题描述】:

自从我发布这篇文章后,我已经休息了一段时间,并且已经阅读了我正在学习的 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(prefer &gt;= 10 &amp;&amp; &lt; 0);语法错误。
  • 你还知道多少个数字可以是&gt;= 10 AND &lt; 0?仔细考虑你需要什么。
  • 无论什么让你认为 C 语言中的“and”和英文中的“and” 词的意思都是一样的,丢掉它吧……给自己买一本像样的书吧。或者,考虑另一种编程语言,尽管您可能会遇到同样的问题。考虑一下“and”在英语中的含义是多方面的。在编程中,通常只有其中一种含义适用。你选择了错误的定义,仅此而已。
  • 其实我的意思不是用“and”,而是用“or”。谢谢。我很感激帮助。我实际上正在关注一本书。显然,不太好......:/
  • 对不起,我是新手。明白了。根据您的建议进行编辑。如果有任何问题,请告诉我。

标签: do-while cs50 cc


【解决方案1】:

运算符&lt;&amp;&amp; 是二元运算符。当我们使用它们时,它会比较左侧和右侧的值。上面的 while 看起来像这样。

while(prefer <= 10 && prefer > 0);

【讨论】:

  • 关键是&amp;&amp;操作符判断两个东西是否都为真,左边的东西和右边的东西。右边是&lt; 0,这不是一个真实的东西,它是比较的一部分。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-29
  • 2019-04-03
  • 2021-03-12
  • 2012-10-18
  • 2015-01-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多