首页 > 解决方案 > 如何在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;
}

标签: c++random

解决方案


只需使用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;

活生生的例子


推荐阅读