|
查看: 1596|回复: 6
|
c++ random number 问题
[复制链接]
|
|
|
这是我的原码-
- #include<iostream>
- #include <cstdlib>
- using namespace std;
- int main(int argc, char *argv[])
- {
- int random[9];
- for (int a = 0;a<9;a++){
- random[a] = (rand()%10)+1;
- cout<<random[a]<<endl;
- }
- }
复制代码 我想问c++每次generate random number 都是一样吗?
为什么每次都execute 同样的四个号码?
我是用 microsoft visual studio 的c++ |
|
|
|
|
|
|
|
|
|
|
发表于 24-4-2008 01:31 PM
|
显示全部楼层
|
|
|
|
|
|
|
|
|
|

楼主 |
发表于 24-4-2008 01:33 PM
|
显示全部楼层
原帖由 KHTAY 于 24-4-2008 01:31 PM 发表 
你要用不同的seed.
什么是seed? |
|
|
|
|
|
|
|
|
|
|
发表于 24-4-2008 01:37 PM
|
显示全部楼层
给你些Info,你可以参考,是英文的。
The sequence of numbers returned by rand() are called random because they satisfy statistical tests for randomness, eg, uniform distribution, coorelation between sequential numbers is zero, no apparent patterns). But of course they really can't be truly random (whatever that means) because computers are deterministic. Therefore they are more properly called pseudorandom numbers.
For a given seed (starting value), the sequence of numbers that rand() returns will always be the same. Because the starting point for the pseudorandom sequence can easily be varied (see below) and because the sequence is very long (perhaps billions before the sequence repeats), these pseudorandom numbers are as good as random.
Having the same sequence generated each time can be useful for debugging, but it isn't very useful when you're actually using the program. To generate a different random sequence, it's necessary to set the seed that starts the sequence. The srand() function takes a positive integer parameter which tells where to start the sequence.
example
int i;
i=srand(2345);
Using the time as a seed - srand(time(0))The standard way to start with a different initial value, the seed, is to use the current time as a seed. Use the time() function as follows:
srand(time(0)); // Initialize random number generator.at the beginning of the program to initialize the random seed. time(0) returns the integer number of seconds from the system clock. This will almost always be a different value.
example:
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
int main() {
srand((unsigned)time(0));
int random_integer = rand();
cout << random_integer << endl;
}
[ 本帖最后由 KHTAY 于 24-4-2008 01:52 PM 编辑 ] |
|
|
|
|
|
|
|
|
|
|

楼主 |
发表于 24-4-2008 01:52 PM
|
显示全部楼层
可以了,不过是C的
#include<iostream>
#include <time.h>
using namespace std;
int main(int argc, char *argv[])
{
int random[10];
srand ( time(NULL) );
for (int a = 0;a<10;a++){
random[a] = ((rand()%4)+1)*100+((rand()%13)+1);
cout<<random[a]<<endl;
}
return 0;
} |
|
|
|
|
|
|
|
|
|
|
发表于 24-4-2008 01:54 PM
|
显示全部楼层
|
|
|
|
|
|
|
|
|
|
发表于 24-4-2008 01:55 PM
|
显示全部楼层
|
|
|
|
|
|
|
|
| |
本周最热论坛帖子
|