Advertisement

Random Number ?

Started by April 14, 2002 02:16 PM
9 comments, last by DonatO 22 years, 5 months ago
Hy, I want that my random number is between 0 e 100 ... how do I make it ? Thx!
The way that I do it, which I don''t think is a very good way personally, is int rand_num = rand()%100;
Advertisement
You should include time.h and add following line to the beginning of your main()-function :

srand((unsigned)time(NULL));

Remember: Only call it once. That should give you more ''random'' numbers.
Thx !!
Yeah, the first response works, but it's really no good.

You'll need to include stdlib.h and time.h.

As the other guy said, you'll want to call
srand((unsigned int)time(0));
once at the start of your code, to randomize the numbers.

Then, to get a random number between 0 and 100, use this:
int RandNum = 101*(rand()/(double)RAND_MAX);

Tada.

Peace,
ZE.

//email me.//zealouselixir software.//msdn.//n00biez.//
miscellaneous links

[if you have a link proposal, email me.]

EDITED for bad wording and a code mistake.

[edited by - zealouselixir on April 14, 2002 4:37:30 PM]

[twitter]warrenm[/twitter]

The last posts method is the same as the first posts but slower (floating point division).

rand(); return a number between 0 and RAND_MAX not including RAND_MAX itself. So a modulus N operation will return 0-N.

,Jay
Advertisement
Corillian: It''s rand()%101 because of the offset. If you used 100 it would be 0-99.
I just got told that the modulus method buggers up on some computers by giving not very random numbers and there is a thread going on over in ''general programming'' that will explain this (Guess where I''m going now....).

,Jay
quote: Original post by Jason Zelos
The last posts method is the same as the first posts but slower (floating point division).


Actually it''s not, and I''d prefer that you get your facts straight before wagging your ignorant tongue.

[twitter]warrenm[/twitter]

I''d have to go with Magriep on this one. His method is easiest to read and gives a good result.

Helpful links:
How To Ask Questions The Smart Way | Google can help with your question | Search MSDN for help with standard C or Windows functions

This topic is closed to new replies.

Advertisement