2017-02-25 58 views
0

我不得不猜测数字游戏的代码,但我不知道如何生成随机数。随机函数只产生负数。如何生成1000和-1000 C++之间的随机数?

的代码,我到目前为止有:

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

using namespace std; 

int main(){ 

    srand(time(NULL)); 

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

    return 0; 

} 
+3

使用['std :: uniform_int_distribution'](http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution)? –

+0

当你从一个从0到999的随机数中减去1000时,负数就会出现=) – hidefromkgb

回答

1

我认为这应该工作,我从我的电脑,距离虽不能测试:

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

的范围[ 。-1000,1000]有2001个选项(假设您想包括两个边界需要由范围的宽度modulu rand()的结果,而加/减一开始即:

int randomNumber = rand() % 2001 - 1000; 
2

我迄今为止只能生成负数的代码。

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

相关问题