【问题标题】:Using enums for modifying print statements in C使用枚举修改 C 中的打印语句
【发布时间】:2021-05-09 04:11:24
【问题描述】:

我对代码的operand 位有疑问。下面的函数让用户 5 次尝试猜测生成在 0 和 20 之间的随机数,用户有 5 次尝试猜对代码。在第二个else 语句中,我想使用enums 修改more,less 关键字,具体取决于用户输入是大于还是小于生成的数字。

代码:

#include <stdio.h>
#include <stdbool.h>

int main ()
{
     int tries = 5;
     int random = rand() %20;
     int input;
     static const char *const comp[] = {[less] = "less",[more] = "more"};
     enum Comparison {more, less};
     enum Comparison operand;

     for(int i=0; i>=tries; --tries){
         printf("You have %d tries left", tries);
         printf("Enter a guess: ");
         scanf("%d", &input);
         if(input > random){
            operand = more;
         }
         else{
            operand = less;
         }
         if (input == random){
            printf("Congratulations. You guessed it!");
            break;
         }
         else{
            printf("Sorry %d is wrong. My number is %d than that", input, comp[operand]);
            continue;
         }
     }
     return 0;
}

错误:

【问题讨论】:

  • 请不要在给出答案或 cmets 后修改您的代码。这使所有努力都无效。
  • 你应该把你的枚举类型声明放在你使用它的行之前。
  • comp[operand] 是一个字符串,但您使用%d 打印它。这会导致未定义的行为,应该让你的编译器尖叫。

标签: c function for-loop if-statement enums


【解决方案1】:

您的代码中没有名为 Comparison 的数组。

您可以将operand = Comparison[0]; 替换为operand = less;,并将operand = Comparison[1]; 替换为operand = more;

错误猜测的printf 看起来有点奇怪。当operand 等于less 时,它将打印“我的操作数比那个0”,或者当操作数等于more 时,它会打印“我的操作数比那个1”。我猜你真的希望printf 打印单词“less”或“more”而不是数字 0 或 1。你可以通过使用数组将枚举值映射到字符串来做到这一点:

    static const char *const comp[] = {
        [less] = "less",
        [more] = "more"
    };

    printf("Sorry %d is wrong. My number is %s than that.\n",
           input, comp[operand]);

【讨论】:

    【解决方案2】:

    Comparison[0] 替换为more,将Comparison[1] 替换为less

    枚举不像 C 中的数组那样工作:)

    编辑:

    这个循环看起来也有问题:

    for(int i=0; i&gt;=tries; --tries)tries 是 5,所以循环永远不会运行,因为 i=0 和 0 永远不会 >= 5。重新考虑这里的逻辑 :)

    【讨论】:

    • @M.M 我现在无法访问编译器,但这让我感到惊讶!今天学到了新东西:)
    • 谢谢我还有一个问题,在打印函数printf("Sorry %d is wrong. My number is %s than that\n", input, operand);它打印出0或1的操作数我希望它打印出moreless我能做什么解决这个问题?
    • @MOehm 我的错,误读了语言标签。 (enum Comparison)0 然后
    • @tony 考虑在 printf 语句中将 , operand 替换为 , operand ? “more” : “less”
    • @M.M:好吧,那从未发生过。 :)(我和 Morten 一样惊讶,仅此而已。)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多