首页 > 解决方案 > 使用枚举修改 C 中的打印语句

问题描述

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

代码:

#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;
}

错误: 在此处输入图像描述

标签: cfunctionfor-loopif-statementenums

解决方案


Comparison您的代码中没有调用数组。

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

错误的printf猜测看起来有点奇怪。operand当等于时,它将打印“我的操作数比那个 0” less,或者当操作数等于 时,它会打印“我的操作数比那个 1” more。我猜你真的想要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]);

推荐阅读