user2555471
user2555471

Reputation: 31

c++ random numbers -100 to 100

I want to generate a list that contains random numbers from -100 to 100. The code I have so far just goes from -50 to 50.

for(int line=0;line<100;line++) //reads individual lines and compares them
{
    ofs<<rand()%101 + (-50)<<endl;
}

I would really appreciate it if someone could point me in the right direction!

Upvotes: 0

Views: 4235

Answers (3)

Gobroski
Gobroski

Reputation: 3

rand() %201 - 100 works just right

Upvotes: 0

jia103
jia103

Reputation: 1134

Note that you want values from -100 to +100, which is a range of 200 values, so you'd really want:

rand() % 200 // possible off-by-one error

This will give you 0..199. To get closer to the range you want, subtract 99:

(rand() % 200) - 99

This will give you the range -99..+100. This is closer to what you want.

You should be able to go back now and tweak to get the range you really want.

Upvotes: 0

TypeIA
TypeIA

Reputation: 17258

Change to %201 and +(-100). A little experimentation would have figured this out.

Upvotes: 2

Related Questions