你好,我只想编写一个程序,从数组中随机选择一个字符,到目前为止,我已经想出了这段代码。我在最后一个printf()处得到一个错误消息help...Thread 1: EXC_BAD_ACCESS (code=1,address=0x48)
#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;
}发布于 2022-04-09 17:20:14
num在最后一个printf中应该是num-1,因为数组中的元素范围是0到5,如下所示
#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;
}https://stackoverflow.com/questions/71810057
复制相似问题