读书人

用函数写的发作随机数糊里糊涂的不知

发布时间: 2013-01-01 14:04:19 作者: rapoo

用函数写的产生随机数,糊里糊涂的不知道对不对?

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int a[5]={0,1,2,3,4},i, b,m;
main()//shuffle 洗牌;licensing 发牌;
{
int shuffle();
shuffle();
for (i=0;i<5;i++)
printf("%d\n",a[i]);

}
shuffle()
{
srand (time(0));
m=rand();
for (i=0;i<5;i++) //洗牌程序
{
b=a[i]; //互换
a[i]=a[m%(5-i)+i];
a[m%(5-i)+i]=b;
}
return 0;
}



其实我是想在函数中返回一个数组中的所有值,但是没学指针,看网上说要用指针返回,然后我就自己瞎改,写了 return 0,最后运行的结果确实是5个数随机排列,但是总感觉在哪不对劲?有谁能指点一下???谢谢了。
[解决办法]
http://hi.baidu.com/qgvyezrmcwbpuwd/item/862063bd8fbaf3ea4ec7fd25
[解决办法]
你这个shuffle过程中就是从5张牌中,拿出第一张和剩下4张中的某一张交换,剩下牌重复这个过程。。。因为你就随机了一次,所以第一张牌位置固定后,其他牌的位置也可推断出来,随机性不够啊。洗牌方法有很多种,下面这个随机性要好点,返回一个指针(数组首地址),c/c++是不能返回数组的所有值的
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int a[5]={0,1,2,3,4},i, b,m;
int main()//shuffle 洗牌;licensing 发牌;
{
int* shuffle();
int *arr = shuffle();
for (i=0;i<5;i++)
printf("%d\n",*arr++);

return 0;

}
int* shuffle()
{
srand (time(0));

for (i=0;i<5;i++) //洗牌程序
{
m = rand()%(5-i)+i;
int tmp=0;
tmp = a[i];
a[i] = a[m];
a[m] = tmp;
}
return a;
}

读书人网 >C语言

热点推荐