首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我试图使用rand()从数组中打印一个随机字符。

我试图使用rand()从数组中打印一个随机字符。
EN

Stack Overflow用户
提问于 2022-04-09 16:51:53
回答 1查看 38关注 0票数 2

你好,我只想编写一个程序,从数组中随机选择一个字符,到目前为止,我已经想出了这段代码。我在最后一个printf()处得到一个错误消息help...Thread 1: EXC_BAD_ACCESS (code=1,address=0x48)

代码语言:javascript
复制
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(){
    int lower = 1, upper = 6;
    int test;
    srand((unsigned int)time(0));

    char*  placeArray[]={"Renti","Mosxato","Tavros","Kallithea","Petralona","Thisio"};
    int i, num;
    for (i=0;i<6;i++){
        num=(rand() % (upper - lower + 1)) + lower;
        test=(int)num;
        printf("%d ",num);
        printf("%s\n",placeArray[num]);

    }
    return 0;
}
EN

回答 1

Stack Overflow用户

发布于 2022-04-09 17:20:14

num在最后一个printf中应该是num-1,因为数组中的元素范围是0到5,如下所示

代码语言:javascript
复制
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(){
    int lower = 1, upper = 6;
    int test;
    srand((unsigned int)time(0));

    char * placeArray[]= {"Renti", "Mosxato", "Tavros", "Kallithea", "Petralona", "Thisio"};
    int i, num;
    for (i = 0; i < 6; i++){
        num = (rand() % (upper - lower + 1)) + lower;
        test = (int)num;
        printf("%d ", num);
        printf("%s\n", placeArray[num - 1]);
    }
    return 0;
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71810057

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档