1.随机数都只能是一次性的,如果你第二次运行的时候输出结果仍和第一次一样。这与srand()函数有关。
#include<iostream>
using namespace std;
#include<stdio.h>
#include<stdlib.h>
#include<ctime>
void main()
{
for (int i = 0; i < 10; i++)
cout << rand() << "\t";
cout << endl;
for (int i = 0; i < 10; i++)
cout << rand() << "\t";
cout << endl;
for (int i = 0; i < 10; i++)
cout << rand() << "\t";
cout << endl;
for (int i = 0; i < 10; i++)
cout << rand() << "\t";
cout << endl;
for (int i = 0; i < 10; i++)
cout << rand() << "\t";
cout << endl;
for (int i = 0; i < 10; i++)
cout << rand() << "\t";
cout << endl;
for (int i = 0; i < 10; i++)
cout << rand() << "\t";
cout << endl;
for (int i = 0; i < 10; i++)
cout << rand() << "\t";
cout << endl;
for (int i = 0; i < 10; i++)
cout << rand() << "\t";
cout << endl;
for (int i = 0; i < 10; i++)
cout << rand() << "\t";
cout << endl;
for (int i = 0; i < 10; i++)
cout << rand() << "\t";
cout << endl;
for (int i = 0; i < 10; i++)
cout << rand() << "\t";
cout << endl;
}
2.srand(time(NULL));
之后调用rand()即可得到0 ~ 32757范围的随机数
包含头文件stdlib.h和time.h 或 cstdlib和ctime
#include <stdlib.h>
#include <time.h>
或
#include
#include
用下列公式即可得到指定范围[m,n]的随机数:
r = rand()%(n - m + 1) + m;
注意:n - m 的绝对值不能超过32767
网上复制的,懒得打字了。。。。
#include<iostream>
using namespace std;
#include<stdio.h>
#include<stdlib.h>
#include<ctime>
void main()
{
for (int i = 0; i < 5; i++)
cout << rand()%10 << "\t";
cout << endl;
for (int i = 0; i < 5; i++)
cout << rand() % 100 << "\t";
cout << endl;
for (int i = 0; i < 5; i++)
cout << rand() % 1000 << "\t";
cout << endl;
for (int i = 0; i < 5; i++)
cout << rand() % 10000 << "\t";
cout << endl;
for (int i = 0; i < 5; i++)
cout << rand() % 100000 << "\t";
cout << endl;
}
#include<iostream>
using namespace std;
#include<stdio.h>
#include<stdlib.h>
#include<ctime>
void main()
{
srand((int)time(0));//生成的随机数都只能是一次性的,如果你第二次运行的时候输出结果仍和第一次一样。这与srand()函数有关
for (int i = 0; i < 5; i++)
cout << rand()%10 << "\t";
cout << endl;
for (int i = 0; i < 5; i++)
cout << rand() % 100 << "\t";
cout << endl;
for (int i = 0; i < 5; i++)
cout << rand() % 1000 << "\t";
cout << endl;
for (int i = 0; i < 5; i++)
cout << rand() % 10000 << "\t";
cout << endl;
for (int i = 0; i < 5; i++)
cout << rand() % 100000 << "\t";
cout << endl;
}