c++怎样用rand使output为随机字母?

来源:百度知道 编辑:UC知道 时间:2024/05/14 18:08:19
如题,c++怎样用rand使output为随机字母?具体点说,我希望output是r,p或者s,这3个字母中的随机选择。谢谢。
回答我问题的高手,非常感谢,可以在post答案的时候顺便讲解下么?谢谢

你需要的可以如下实现
int type;
char ch;

srand(time(0));

type = rand() % 3;

switch (type) {
case 0:
ch = 'r';
break;
case 1:
ch = 'p';
break;
case 2:
ch = 's';
break;
default:
;
/* error */
}

cout << "ch = "<< ch<<endl;

int type;
char ch;

srand(time(0)); //利用时间为rand设置seed值,避免每次运行产生相同的结果

type = rand() % 3; //调用rand()函数生成一个随机数,模3之后可以得到0-2的一个数,再利用switch决定是哪个字母

switch (type) {
case 0:
ch = 'r';
break;
case 1:
ch = 'p';
break;
case 2:
ch = 's';
break;
default:
;
/* error */
}