C语言中怎么产生三个互不相同的随机数 求代码

如题所述

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{
    int i, vis[100] = {0}, tot = 3;
    srand((int)time(0));
    for(;tot;)
    {
        int index = rand() % 100;
        if(!vis[index])
        {
            printf("%d ", index);
            vis[index] = 1;
            tot--;
        }
    }
    return 0;
}

 

温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-07-17
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
    int a,b,c;//保存3个随机数
    srand((unsigned)time(NULL));
    a=rand()%10;//产生一个0~9的随机数
    while(1)//产生一个不等于a的0~9的随机数
    {
        b=rand()%10;
        if(b!=a) break;
    }
    while(1)//产生一个不等于a和b的0~9的随机数
    {
        c=rand()%10;
        if((c!=a) && (c!=b)) break;
    }
    printf("a=%d,b=%d,c=%d\n",a,b,c);
    return 0;
}

第2个回答  2014-07-17
srand((int)time(NULL));设定随机数种子
rand()%100;产生0-99的随机数。高级点的,假如要产生16-59之间的数,你可以这样写:rand()%44+16(这里44由59-16+1得到)。其他情况如法炮制!
相似回答