如何生成1000到-1000 c ++之间的随机数?

时间:2017-02-25 20:09:10

标签: c++ random

我必须编码猜数字游戏,但我不知道如何生成随机数。随机函数只生成负数。

到目前为止我的代码:

#include <iostream>
#include <stdlib.h>
#include <time.h>

using namespace std;

int main(){

    srand(time(NULL));

    int N=rand()%1000+-1000;

    return 0;

}

3 个答案:

答案 0 :(得分:2)

  

到目前为止,我的代码只生成负数。

rand()%1000的最大值为999。如果您向其添加-1000,它将始终为负数。试试rand() % 2001 - 1000

答案 1 :(得分:1)

我认为这应该有效,我离开了我的电脑并且无法测试它:

(rand()%(max-min))+min;

答案 2 :(得分:1)

[-1000,1000]的范围有2001个选项(假设您想要包含两个边界。您需要根据范围的宽度模拟rand()&s;结果和加/减它的开始。即:

int randomNumber = rand() % 2001 - 1000;
相关问题