rand()生成相同的数字 [英] rand() generating the same number

查看:194
本文介绍了rand()生成相同的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

rand函数返回相同的值c ++

为什么rand()产生相同的数字?

Why is rand() generating the same number?

die.h

#ifndef DIE_H
#define DIE_H


class Die
{
private:
    int number;
public:
    Die(){number=0;}
    void roll();
    int getNumber()const{return number;}
    void printValue();
};

#endif

die.cpp

#include"die.h"
#include<iostream>
#include<time.h>
using namespace std;

void Die::roll()
{
    srand(static_cast<int>(time(0)));
    number=1+rand()%6;
}

void Die::printValue()
{
    cout<<number<<endl;
}

main.cpp

#include"die.h"
#include<iostream>
using namespace std;

int main()
{
    Die d;
    d.roll();
    d.printValue();
    d.roll();
    d.printValue();
    d.roll();
    d.printValue();
}


推荐答案

$ c> die.roll()如此接近, time(0)实际上每次都返回相同的值,因此,您的rand种子对于 .roll()的每次调用都是相同的。

Your calls to die.roll() are so close together that time(0) is actually returning the same value every time, and, thus, your rand seed is the same for each call to .roll().

尝试调用 .roll()之外一次(并且只有一次)(如下所示):srand(static_cast< int>(time(0))); Die构造函数或 main())。

Try calling srand(static_cast<int>(time(0))); once (and only once) outside of .roll() (like in the Die constructor or main()).

这篇关于rand()生成相同的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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