【问题标题】:Adding second "while (bool exp) give strange result添加第二个“while(bool exp)会产生奇怪的结果
【发布时间】:2020-06-06 08:17:39
【问题描述】:

我的任务是将输出机会限制在 1 到 8 之间。如果玩家按下少于 1 或更多 8 程序必须将他返回到选择选项。

在添加第二个while 循环并在没有任何错误的情况下编译后,程序会为 oportunity 输入任何值,并在 1 到 8 之间的值以及当我们尝试输入小于 1 时适当地工作。但是当用户输入时,情况会变得非常奇怪超过 8 个。

谁能解释为什么?

#include <stdio.h>
#include <cs50.h>

int main(void)
{
    int n;
    do
    {
        n = get_int("Height:");
    }
    while (n < 1);
    while (n > 8);
    for (int i = 0; i < n; i++)
    {
        for(int j = 0; j < n; j++)
        {
            printf("#");
        }
        printf("\n");
    }

}

【问题讨论】:

  • 请不要将代码和其他文本输出作为图像或图像链接发布 - reasoning。请将其作为格式化文本粘贴到问题中。
  • while (n&gt;8); 是一个没有主体的循环,也就是说,它所做的只是不断检查条件,直到它变为假。由于在该循环中n 没有任何变化,因此如果条件开始为真,显然会导致无限循环。相反,你想要do { ...} while (n&lt;1 || n&gt;8);

标签: c loops cs50


【解决方案1】:

你有

do { n = ...; } while (n < 1);

while (n > 8);

这个和

一样
do { n = ...; } while (n < 1);

while (n > 8) { }

如果n &gt;= 1 为真,则退出第一个循环。

如果n &gt; 8 也为真,则进入第二个循环。由于在第二个循环中n 没有任何变化,因此条件永远不会变为假,因此它会无限循环。

你在寻找

do { n = ...; } while (n < 1 || n > 8);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-08
    • 2015-10-04
    • 2013-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-28
    相关资源
    最近更新 更多