C++获取随机数
-
使用 Rand() 函数。
int _tmain(int argc, _TCHAR* argv[]) { for (int i = 0; i < 5; i++) { //随机数大小 0-RAND_MAX, 值为2147483647,定义在stdlib中。 cout << rand() << endl; } for (int i = 0; i < 5; i++) { //若获得一定范围内的数值,则结合%和/来实现 cout << rand() % 10 << endl; // 生成1-10的随机数 } //这样获得的随机数都是一定的,每次运行都一定,不会发生变化。 system("pause"); return 0; }
-
使用 srand() 获得随机的。
#include <iostream> #include <ctime> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { //引入ctime库 time(0)是获取从1970年开始的时间(单位:s) srand(time(0)); for (int i = 0; i < 5; i++) { //随机数大小 0-RAND_MAX, 值为2147483647,定义在stdlib中。 cout << rand() << endl; } for (int i = 0; i < 5; i++) { //若获得一定范围内的数值,则结合%和/来实现 cout << rand() % 10 << endl; // 生成1-10的随机数 } //这样获得的随机数都是一定的,每次运行都一定,不会发生变化。 system("pause"); return 0; }
参考链接:c++获取随机数