C语言如何从二维char数组fruits中获取随机单词并正确打印
错误原因与修正方案
你代码的问题集中在类型不匹配和格式符误用:
- 存储随机结果的
random变量类型错误:你声明为char仅能存单个字符,而fruits[下标]获取到的是字符串的首地址,需要修改为char*类型 printf格式符使用错误:%c仅用于输出单个字符,输出完整字符串需要使用%s格式符- 额外补充:
srand、rand函数依赖<stdlib.h>头文件,time函数依赖<time.h>头文件,你的原始代码缺失这两个头文件引用,部分编译器会直接编译报错。
修正后可运行代码
#include <stdio.h> #include <stdlib.h> #include <time.h> int main() { srand(time(NULL)); int isSpin; char* random; printf("To spin the wheel input 1\n"); scanf("%d", &isSpin); char fruits[4][10] = {"bell", "orange", "cherry", "horseshoe"}; if (isSpin == 1) { random = fruits[rand()%4]; printf("%s", random); } else { printf("You didn't spin"); } return 0; }
内容的提问来源于stack exchange,提问作者FUZION
相关产品推荐
相关产品推荐

