c++ - 如何在c ++中获取5到-5之间的随机数
问题描述
我正在尝试使用它来获取随机数rand % (5 -5)
,它给出了除以零的错误
#include <iostream>
using namespace std;
int main()
{
int A[20];
for (int i-=0 ;i<20;i++)
A[i]= rand() % -5;
system("pause")
return 0;
}
解决方案
只需使用std::uniform_int_distribution
产生随机整数值 i,均匀分布在闭区间 [a, b]...
std::random_device rd; //Will be used to obtain a seed for the random number engine
std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
std::uniform_int_distribution<> dis(-5, 5);
std::cout << dis(gen) << std::endl;
推荐阅读
- android - Xamarin.Forms:在地图点击时隐藏 ListView?
- c# - Visual Studio 2017 设计器视图不显示控件
- excel - 按主题搜索所有文件夹中的最新电子邮件并全部回复
- javascript - 表格未提交正确的数据
- asp.net-core-mvc - 如何修复从 Postman 中的 PUT json 发送的空对象?
- c# - 删除事件不是从角度调用 get 方法调用
- r - 在 Stargazer 表中包含标准化系数
- c# - 如何使代码显示信息?
- javascript - 是什么 !vue/typescript 应用程序中的符号
- angular - 隐藏加载器之前的图像加载