C语言从{0,1,2,3,4}的数组中随机抽取3个数的源程序

如题所述

//这种方法是不重复抽取,重复抽取更简单
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int arr[5] = { 0, 1, 2, 3, 4 };
bool barr[5] = { false };
int iarr[3];

srand(time(0));
int count = 0;
while(count < 3)
{
int val = rand() % 5;
if(barr[val] == false)
{
iarr[count] = arr[val];
count++;
barr[val] = true;
}
}

for(int i = 0; i < 3; i ++)
{
printf("%d ", iarr[i]);
}

return 0;
}

//追问

运行不出来呀?

追答

你编译能通过么?提示的错误是什么
复制后要让
#include
#include
#include

这三行独立成行,不要有其他代码和他们在同一行

追问

E:\VC++\MSDev98\MyProjects\sd\as.c(6) : error C2065: 'false' : undeclared identifier
E:\VC++\MSDev98\MyProjects\sd\as.c(15) : error C2065: 'true' : undeclared identifier
sd.exe - 1 error(s), 0 warning(s)

追答

你应该是手抄的把,要不复制一遍试试,这个错误可能是单词出错,我在vs2005运行确实是没问题的

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-03-26
/*
比较有效率的方法
*/

int* getout ()
{
const int out[][]={{0,1,2},{0,1,3},{0,1,4},{0,2,3},{0,2,4},{0,3,4},{1,2,3},{1,2,4},{1,3,4},{2,3,4}} ;
return &out[rand () % 9][0] ;
}
第2个回答  2013-03-26
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int getRand(int arr[],int len)
{
srand(time(0));

int val = rand() % len;

return arr[val];
}

int main(int argc,char *argv[])
{
int arr[5] = { 0, 1, 2, 3, 4 };

for(int i=0; i< 3; ++i)
{
printf(" i= %d\n",i,getRand(arr,sizeof(arr));
}
getchar();
exit(0);
}
第3个回答  2013-03-26
你先随机这个数组的下标 然后再将下标转换为数组中的数字 再将其输出 相信你现在会写了吧
相似回答