c++中的随机整型
Random int in C++
我刚刚用c++写了下面的代码,但我有一个问题:随机出现的数字总是相同的…!!下面是我的代码和截图:
#include <iostream>
using namespace std;
int main() {
cout << "I got a number in my mind... can you guess it?" << endl;
int random;
random = rand() % 20 + 1;
cout << random << endl;
system("pause");
return 0;
}
截图:http://tinyurl.com/n49hn3j
srand(time(0))
只会产生一个新的随机数,如果你不启动它在同一秒你做了最后一次。使用rand() % 20也有问题。这会做正确的事情:
#include <iostream>
#include <random>
int main(){
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_int_distribution<int> dist(1, 20);
std::cout << dist(mt);
}
您需要使用srand
函数初始化(种子)随机。更多信息
#include <iostream>
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
using namespace std;
int main() {
// Seed the random number generator
srand(time(0));
cout << "I got a number in my mind... can you guess it?" << endl;
int random;
random = rand() % 20 + 1;
cout << random << endl;
system("pause");
return 0;
}
试试这个:
#include <ctime> //for current time
#include <cstdlib> //for srand
srand (unsigned(time(0))); //use this seed
这也将适用于您的随机。
相关文章:
- C 字符串返回字符串的整数/双精度/长整型值
- 是什么导致了这种使用三进制而不是短整型的有符号int到无符号int转换
- 无法在 Arduino 中uint8_t数组转换为无符号长整型数组
- JNI 日期值转换问题,在C++中获取不同的长整型值
- 将长整型值打印为带有前导零的十六进制
- 为什么在传递长整型时调用具有两个双精度类型的参数的重载函数?
- 将整型常量映射到类型
- 将元组和整型实例合并到引用元组中
- 提升不良词法强制转换:将字符串转换为无符号长整型时,无法将源类型值解释为目标
- 为什么C++不允许两个同名的函数/类模板,区别仅在于非类型模板参数(整型)的类型?
- 将最小值整数转换为无符号长整型
- 如何将小端格式的QByteArray转换为无符号长整型
- 直接初始化无符号短整型的标准行为
- 无符号长整型和无符号 int 之间有什么区别,这 2 种类型应该如何在 c# 中封送?
- 无符号和有符号短整型的位宽
- 将整型转换为浮点型时检测溢出
- 环礁和(长整型)的区别?
- 为什么允许将整型、枚举和指向成员的指针类型reinterpret_cast到自身?
- 生成随机整型和双精度的c++模板类
- c++中的随机整型