【发布时间】: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