生成一个随机数

来源:互联网 发布:502 bad gateway nginx 编辑:程序博客网 时间:2024/06/11 13:37

生成一个随机数需要rand()函数来获得随机整数,使用rand()函数需要添加头文件cstdlib。rand()生成的最大数由平台决定的常输,在vc++中最大数为32767。

rand()函数生成的是伪随机数。即每次在同一个系统上执行这个函数,rand()函数生成同一序列的数(cout<<rand()<<endl<<rand()<<endl<<rand()<<endl;)因为rand()函数的算法使用一个叫种子的值来控制生成的数字,默认情况下,种子值为1。改变种子的值随机数也会改变,srand(seed)函数改变种子的值,为确保每一次种子值不一样,可以使用time(0)。time(0),返回格林尼治时间1970年1月1号00:00:00到现在的秒数。

显示一个随机种子生成的随记整数,strand(time(0));                    cout<<rand()<<endl;

例如:未获得一个0~9的随记整数

#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
int main()
{
srand(time(0));
int a = rand() % 10;
int b = rand() % 10;
if (a < b)
{
int c = a;
a = b;
b = c;
}
cout << "what is" << a << "-" << b << "?"<<endl;
int answer;
cin >> answer;
if (a - b == answer)
cout << "you are cprrect" << endl;
else
cout << "your answer is wrong" <<endl<< a << "-" << b << "should be" << (a - b) << endl;
return 0;
}