c - 使用枚举修改 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;
}
解决方案
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]);
推荐阅读
- spring-boot - 每当我在标头中发送访问令牌时,Docker spring boot 返回 401
- powershell - 设置内容附加到其他文件
- plotly - 在 Axes 坐标之间添加标签
- python - 在 .xlsx 文件中创建新工作表
- spring - Kafka Stream:无法从 Kafka 持久 keyValue 状态存储中获取数据
- maven - Maven WebService 客户端依赖
- react-native - 用按钮反应本机打开抽屉
- json - 为什么我的 WordPress 域只能在没有 www 的情况下使用,而不能与 www 一起使用?
- java - 负数的 BigInteger 求幂失败
- python-3.x - 使用 Functools(部分)清除小部件。lambda会起作用吗