首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

产生不相等随机数的过程为什么这么慢?解决方法

2012-03-03 
产生不相等随机数的过程为什么这么慢?#include stdio.h#include conio.h#include stdlib.h#include

产生不相等随机数的过程为什么这么慢?
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <time.h>
int   function7(void)
    {
    int   i;
    srand(time(NULL));
    i=rand()%33+1;
    return   i;
    }
int   function3(void)
    {
    int   i;
    srand(time(NULL));
    i=rand()%9+1;
    return   i;
    }
int   main(void)
{
int   a[6],n,i,j;
printf( "this   program   is   used   to   count   some   random   numbers\n ");
printf( "Please   choose   which   kind   of   numbers   you   want   to   count\n ");
printf( "|------------------------------------------|\n ");
printf( "|     (1)   Choose   7   numbers   between   1   to   33         |\n ");
printf( "|     (2)   Choose   3   numbers   between   1   to   09         |\n ");
printf( "|------------------------------------------|\n ");
scanf( "%d ",&n);
if(n==1)
    {
    for(i=0;i <7;i++)
        {
        a[i]=function7();
        for(j=0;j <i;j++)
            {
            if(a[i]==a[j])
{
i--;j=0;break;
}
            }
        }
    for(i=0;i <7;i++)
    printf( "%02d     ",a[i]);
    getch();
    }
if(n==2)
    {
    for(i=0;i <3;i++)
        {
        a[i]=function3();
        for(j=0;j <i;j++)
            {
            if(a[i]==a[j])
{
i--;j=0;break;
}
            }
        }
    for(i=0;i <3;i++)
    printf( "%02d     ",a[i]);
    getch();
    }
return   0;
}
上面这几行,为什么运行起来很慢很慢?虽然问题很傻,但新手,不怕丢脸.

[解决办法]
int function7(void)
{
int i;
srand(time(NULL));
i=rand()%33+1;
return i;
}

是你的srand(time(NULL));这里的问题, 虽然每次都设置了随即种子, 但是时间很快,time(NULL)也不够精确, 所以每次time(NULL)都一样..
可以试试这样...
int function7(void)
{
int i;
static int clock = time(NULL);
srand(clock++); //每次都变
i=rand()%100+1;
return i;
}
这样就很快了....
[解决办法]
time(NULL)在他的最小单位时间后才变, 在最小单位内每次随即的数都一样,
所以你上面的 时间 其实就是你的数组的个数 n*time(NULL)的最小单位时间

热点排行