View Single Post
  #4 (permalink)  
Old 07-27-2007, 01:13 AM
rpgfan3233 rpgfan3233 is offline
PT Staff
Awards Showcase
Quality Tutorial Quality Tutorial Quality Tutorial Quality Tutorial 
Total Awards: 4
Join Date: Jul 2007
Posts: 118
iTrader: (0)
rpgfan3233 has a spectacular aura aboutrpgfan3233 has a spectacular aura aboutrpgfan3233 has a spectacular aura aboutrpgfan3233 has a spectacular aura aboutrpgfan3233 has a spectacular aura about
That's why I just memorize the expression and use that.

In old-fashioned QuickBASIC (MS-DOS days), the keyword RND returned a float (a SINGLE, as in single-precision floating-point type) between 0 and 1. To change the values, you actually had to multiply rather than use the modulus operator:
Code:
CLS 'clear the screen
DIM Rand AS INTEGER
Rand = 1 + FIX(RND * 6)
PRINT Random 'print the value to the screen
END 'end the program
Note that the same idea that is used in C (MAXVALUE - MINVALUE + 1) works in QuickBASIC, right down to the addition of the MINVALUE to balance things out. Of course, FIX () in QuickBASIC is needed because otherwise Rand would hold a float/SINGLE when we would want an INTEGER.

As for why the "- min_value + 1" thing is there, consider this:
You want to generate some random data between 50 and 100 to test a grade program. Look at what could happen if we used just 50 for min_value and 100 for max_value, with no "- min_value + 1" added on:
50 + (rand() % 100)
50 + (98) //98 is less than 100...
148

But your range is supposed to be 50 to 100!! Now if you try with the "- min_value + 1" added back in:
50 + (rand() % (100 - 50 + 1))
50 + (rand() % 51)
50 + (49) //49 is less than 51...
99

See? If rand() generates a multiple of 51, including 0, it will result in the lowest value (50).


Edit: The part about GNU C++ and Visual Studio, it is actually more platform specific in that instance. GNU C++ on Windows uses Windows libraries at this time. This means that RAND_MAX on Windows is 32767 (0x7FFF). RAND_MAX on Linux is 2147483647 (0x7FFFFFFF).

__________________
"C makes it easy to shoot yourself in the foot; C++ makes it harder, but when you do it blows your whole leg off."
-- Bjarne Stroustrup, creator of what is now known as C++
For more quotes by Bjarne Stroustrup, check out http://www.research.att.com/~bs/bs_faq.html#really-say-that.
Digg this Post! Del.Icio.Us this Post! Technorati this Post! Furl this Post! Mister Wong this Post! Newsvine this Post! Spurl this Post! Reddit this Post! Netscape this Post!

Last edited by rpgfan3233 : 07-27-2007 at 09:06 AM. Reason: Added in a comment and fixed my FIX () function (X and ( together create a smiley. :P)
Reply With Quote
The Following User Says Thank You to rpgfan3233 For This Useful Post:
HelloWorld (07-27-2007)