You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 18:54:03