Problem with "for" and "rand()"

I'm trying to generate 10 numbers between 56 and 34, however when I execute the 10 numbers generated are outside the range for some reason, I can't find the error. I tried with a different variable outside the "for" and it generates number inside the wanted range..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main ()
{
	int x;
	int counter;
        int y;

	srand(time(NULL));

	y = rand()%3+1;

	cout << "test--->" << y << endl;

	for (counter=0; counter<10; counter++)
	{
		x = rand()%56+34;
		cout << x << endl;
	}

system("pause");

    return 0;


Thanks for any help.
You're not generating between 34 and 56, you're generating between 34 and 90.

To get the range [x,y]: int myRand = rand()%(y-x)+x;

P.S.: Don't use system()!
http://www.cplusplus.com/articles/j3wTURfi/
Last edited on
Thanks a lot, appreciate your help.
1
2
3
4
5
int low = 	//low range
int high =  //high range
int range = (high - low) + 1;

int random = low + int(range*rand()/(RAND_MAX+1)); 


Or something like this?
Topic archived. No new replies allowed.