【问题标题】:(C programming) while loop only works in a specific order(C 编程)while 循环仅按特定顺序工作
【发布时间】:2019-12-04 20:02:13
【问题描述】:

我正在写一个愚蠢的代码作为一个笑话,有点像猜数字。我认为这很好,直到我意识到只有当我按特定顺序输入数字时才会打印正确的东西。我有点初学者,所以我不确定为什么只有按顺序输入数字才能正确打印。这是一般的while循环的条件吗?有没有办法解决这个问题,这样数字的顺序就无关紧要了?任何见解将不胜感激。

这是我的代码:

#include <stdio.h>
#include <math.h>
#include <unistd.h>
#include <string.h>

int number;

int main()
{
    printf("Enter a number!\n");
    scanf("%d", &number);

    while ((number != 69) && (number != 420))
    {
        printf("hmmm, not the number i was looking for... Enter another number!\n");
        scanf("%d", &number);

        while (number == 666)
        {
            printf("what are you, emo? try again!\n");
            scanf("%d", &number);
        while (number == 420)
        {
            printf("lol close, try the other Funny Number\n");
            scanf("%d", &number);

        while ((number != 69) && (number != 420))
        {
            printf("hmmm, not the number i was looking for... Enter another number!\n");
            scanf("%d", &number);
        }
            while (number == 69)
            {
                printf("haha nice\n");
                return 0;
    }
        }
    }
    }
}

【问题讨论】:

  • “猜数字”并没有准确地告诉我们程序应该做什么。细节在编程中很重要。我们需要准确的描述。请提供准确的输入、预期输出和实际输出。
  • 看起来您在许多应该使用if 的地方使用while。对您的最佳建议是在调试器中运行您的程序并逐步执行以更好地了解代码在做什么。并使用一致的缩进更好地格式化您的代码 - 这实际上非常重要,不仅对于代码可读性而且能够检查您的逻辑结构是否正确。
  • 如果您对程序应用一致的缩进,您可能会对其内部工作有一个全新的认识。

标签: c loops while-loop


【解决方案1】:

您可能遇到的是输入一个数字,然后它陷入“内部”循环扫描和检查并失败内部条件而不是所有条件。

我不确定您是否还没有发现 if/else if/else 但这通常是您检查条件语句的方式。我将用伪代码编写此代码,让您有机会自己用 C 编写它。

number = 0
print "Enter a number"
while number != 69
    number = get number
    if number == 666
        print "What are you..."
    else if number == 420
        print "lol close..."
    else if number == 69
        print "haha nice..."
    else
        print "hmmm..."

若想获得更多乐趣,请查看 switch 语句。

【讨论】:

  • 谢谢@foreverska,我修好了!
猜你喜欢
  • 2021-05-07
  • 1970-01-01
  • 1970-01-01
  • 2014-04-01
  • 2015-04-11
  • 1970-01-01
  • 2022-06-10
  • 2022-01-14
  • 1970-01-01
相关资源
最近更新 更多