n00b
n00b

Reputation: 17

How to generate a random number between 1000 and -1000 c++?

I have to code guess the number game but I don't know how to generate the random number. The random function only generates negative numbers.

The code I have so far:

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

using namespace std;

int main(){

    srand(time(NULL));

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

    return 0;

}

Upvotes: 0

Views: 3652

Answers (3)

user7551301
user7551301

Reputation:

I think this should work, I'm away from my computer and can't test it though:

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

Upvotes: 1

robert
robert

Reputation: 3726

The code that I have so far only generates negative numbers.

The maximum of rand()%1000 is 999. If you add -1000 to it, it will be always negative. Try rand() % 2001 - 1000.

Upvotes: 2

Mureinik
Mureinik

Reputation: 311583

The range of [-1000,1000] has 2001 options (assuming you want to include both boundaries. You need to modulu rand()'s result by the width of the range, and add/subtract its beginning. I.e.:

int randomNumber = rand() % 2001 - 1000;

Upvotes: 1

Related Questions