while循环中的随机数[C编程] [英] random number in while loop [C programming]

查看:71
本文介绍了while循环中的随机数[C编程]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在每次循环发生时创建2个随机数(0-4和0-10之间),但是它总是给出相同的数字.如果我多次运行该程序,它将给出不同的数字,但是while循环始终会生成相同的2个数字.谢谢.

I'm trying to create 2 random numbers (between 0-4 and 0-10) in each time the cycle occurs, but it always give the same number. If I run the program multiple times, it gives different numbers, but the while cycle always generates the same 2 numbers. thanks.

int random(int range){
    int num;
    srand(time(NULL));
    num = rand() % range;
    return num;
}

int main(){

    int cnt = 0;
    int i;  
    int j;
    while (cnt <= 20) {
        i = random(5);
        j = random(10);
        printf("%d\n",i);
        printf("%d\n",j);
        printf("\n");
        cnt += 1;
    }
    return 0;
}

推荐答案

您只需为随机数生成器播种一次.

You only need to seed the random number generator once.

因此,请在您的随机函数之外运行此行:

So run this line outside of your random function:

srand(time(NULL));

..在您的主要功能中:

.. in your main function instead:

int random(int range){
    int num;
    num = rand() % range;
    return num;
}

int main(){
    int cnt = 0;
    int i;    
    int j;

    // Seed random number generator
    srand(time(NULL));

    while (cnt <= 20){
        i = random(5);
        j = random(10);
        printf("%d\n",i);
        printf("%d\n",j);
        printf("\n");
        cnt += 1;
    }
    return 0;
}

这篇关于while循环中的随机数[C编程]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆