【发布时间】:2012-11-21 19:17:54
【问题描述】:
可能重复:
rand function returns same values when called within a single function c++
为什么 rand() 生成相同的数字?
死.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();
}
【问题讨论】:
-
使用一次
srand。它目前正在一遍又一遍地播种相同的序列。 -
补充@chris 所说的,这里的关键是
srand被快速连续调用,因此time总是返回相同的值。在打电话给srand之前先睡一会(大约一秒钟),你就会看到行为发生了变化。
标签: c++ visual-c++