C/c++中如何产生指定的随机字符

随机输出a、s、p 三个字符中的任意一个~

C/c++中如何产生指定的随机字符,方法为:

    将指定的字符存储到字符数组a中,字符个数为n。

    生成[0-n)的随机数 i=rand()%n

    按随机数取数组元素  a[i]

参考代码:

#include <stdlib.h> //rand srand
#include <stdio.h>
#include <time.h>
void main()
{
    char a[]="asp" ;
    int n=3;
    int i;
    srand(time(NULL)); //随机种子
    i=rand()%n ;
    printf("%c\n", a[i] );
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2016-06-01
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void main()
{
char a[] = {'a','s','p'};
int i,idx;

srand(time(0));////随机数种子
for(i = 0; i < 10; i++)////假设需要输出10个
{
idx = rand()%3;///3是字母表的个数,求余数的结果为0,1,2
printf("%c\n", a[idx]);
}

}追问

只随机输出一个字符,然后把这个字符赋予一个变量

本回答被提问者采纳
第2个回答  2011-06-21
u ?
??7 ??d m ?? ] ???V ???e ??F   ?~ ? i  ? ??n g ?Q ' ? ?? ?Press any ke
y to continue
#include "stdio.h"
#include "stdlib.h"
#include "time.h"

main()
{
int i;
srand((unsigned)time(NULL));
//数字 大小写 字符 都有 限定范围可生成 指定 大写 小写 数字 字符
for (i=0;i<50;i++)
{
printf("%c ",rand()%256);
}
}
第3个回答  2011-06-21
srand(time());
int i = rand() %3;
switch(i)
{
case 0:
printf("a“);
break;
case 1:
printf("s“);
break;
case 2:
printf("p“);
break;
}
关键是rand()随机函数的使用 rand() %3 产生一个 0-2的随机 数

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网