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()).