c++随机抽取名字?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c++随机抽取名字?相关的知识,希望对你有一定的参考价值。
如何做一个软件,能从90人中随机抽10人不重复,且能公布人名
首先需要一个容器来容纳这九十个名字可以用c++11的array,要记得头文件(vector也行,慢一点)
当然老老实实用数组也行
接着就是随机抽取了
randNum = rand() % (high - low + 1) + low;
randNum是我们要的随机数,rand()是一个空类型函数,需要#include<cstdlib>
high和low自然就是上下限咯,在这里应该是0和89
虽然上面的一小段程序不是完完全全随机的,不过足矣,并且简单
再就是每个randNum不能一样
这个比较不好整,我还没想到好的方法
就暴力呗
每生成一个就与前面的判断
相等就重新生成
抽到是个就输出就是了 参考技术A
由于临时起90个汉字名字有点困难,这里就用“零一”~“玖十”来代替。算法还是要有一点技巧的,不然可能会很慢。所以若帮助了你,请采纳(采纳时可不要点错了哟)。
代码文本:
//#include "stdafx.h"//vc++ 6.0? Maybe should add this line.
#include <stdlib.h>
#include <string>
#include <iostream>
#include "time.h"
using namespace std;
int main(int argc,char *argv[])
string ple[90]="零一","零二","零三","零四","零五","零六","零七","零八","零九","壹十",
"壹一","壹二","壹三","壹四","壹五","壹六","壹七","壹八","壹九","贰十",
"贰一","贰二","贰三","贰四","贰五","贰六","贰七","贰八","贰九","叁十",
"叁一","叁二","叁三","叁四","叁五","叁六","叁七","叁八","叁九","肆十",
"肆一","肆二","肆三","肆四","肆五","肆六","肆七","肆八","肆九","伍十",
"伍一","伍二","伍三","伍四","伍五","伍六","伍七","伍八","伍九","陆十",
"陆一","陆二","陆三","陆四","陆五","陆六","陆七","陆八","陆九","柒十",
"柒一","柒二","柒三","柒四","柒五","柒六","柒七","柒八","柒九","捌十",
"捌一","捌二","捌三","捌四","捌五","捌六","捌七","捌八","捌九","玖十";
int f[90],i,k,t;
for(i=0;i<90;f[i]=i++);
cout << "本次选出的十个人分别是:\\n";
srand((unsigned)time(NULL));
for(i=0;i<10;i++)
cout << ple[f[k=rand()%(90-i)]] << (i<9 ? ' ' : '\\n');
t=f[k],f[k]=f[89-i],f[89-i]=t;
return 0;
以上是关于c++随机抽取名字?的主要内容,如果未能解决你的问题,请参考以下文章