random numbers problem

Hi guys. I'm trying to get a specific random number. Example, the number of 25, 30, 35, 40, 45, 50, need to be pick randomly and assign to x. I have made the code, but does not work. There is no error. So, what is wrong with my code? Please help. Thank you.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

int main()
{
	int x;
	do{
		srand(time(NULL));
		x = rand() %25+25;
	}while(x!=25||x!=30||x!=35||x!=40||x!=45||x!=50);
	cout << x;

	return 0;
}
Last edited on
Well, look at your condition again. If x is equal to one of the numbers, it's different from all the others.
Ergo, your condition is always true.

Although you're probably better off without the loop anyway.
x=rand()%(10-5+1)*5+25;
Last edited on
Can you please explain what is wrong with my condition?


Edit:

Okay, it runs good now. Thank you.
Last edited on
Only use srand(time(NULL)) once (i.e put it at the start of int main()). If you are doing it in the loop, then you are seeding your random number generator with the same input (time which is not really changing at this rate) over and over. That means you will get the same output over and over.

I would replace lines 9-12 with this:
1
2
srand(time(NULL));
x = ((rand()%6)+5)*5);


rand%6 is used because you want 6 discrete values. (0,1,2,3,4,5)
I then translate it up 5 to get (5,6,7,8,9,10)
and then multiply by 5 to get (25, 30, 35, 40, 45, 50)

If you are specifically asking about your particular exit condition from the loop (which is a valid yet ineffecient method of doing this), listen to what Athar said. Replace the line:
}while(x!=25||x!=30||x!=35||x!=40||x!=45||x!=50);
with
}while(!(x==25||x==30||x==35||x==40||x==45||x==50));
Check out DeMorgan for more information about boolean algebra like this.
Last edited on
@Stewbond, thank you for the explanation. Your condition work, but the random don't. But, i have try different condition with @Athar random statement. And it work. Here is my version.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

int random(int low_limit, int high_limit)
{
	int x;
	do{
		x=rand()%(10-5+1)*5+25;
	}while(!(x!=low_limit || x!=high_limit));
	return x;
}

int main()
{
	srand(time(NULL));
	cout << random(25,50) << endl;
	return 0;
}


But, please explain to me, what the random statement be if i want to change the low_limit to 50 and the high_limit to 100, instead of 25 and 50.
Last edited on
Basically, you'd want multiples of 5, between 50 and 100, right... So I guess this would work:

x=(((rand()%11)+10)*5)

By the same logic as Stewbond's...
1) rand()%11, would give me 11 values, from 0 to 10,
2) (rand()%11)+10 would translate it up to 10 to 20.
3) ((rand()%11)+10)*5 would multiply the limits, thereby giving multiples of 5 b/w 50 and 100...
Topic archived. No new replies allowed.