What would you do to get a random number from say, 1 to 5? I know the function is called rand(), but I don't know how to use it.
What would you do to get a random number from say, 1 to 5? I know the function is called rand(), but I don't know how to use it.
Ignoring all of the sticky issues that can come up:
You'll run into the sticky issues in the following order:Code:#include <cstdlib> #include <iostream> using namespace std; int main() { for (int i = 0; i < 10; i++) cout<< rand() % 5 <<endl; }
- The same random sequence each time the program is run (use srand)
- The numbers may not be that random (don't use modulus)
- rand sucks (get a better random number generator)
Conveniently enough, the first two are the most common, and they're answered in the FAQ. The last is a problem that you'll only run into when you're good and ready to tackle it, so no worries at this point.
My best code is written with the delete key.
shouldn't you be usingto get a range of 1..5?Code:1+rand()%5;
Join is in our Unofficial Cprog IRC channel
Server: irc.phoenixradio.org
Channel: #Tech
Team Cprog Folding@Home: Team #43476
Download it Here
Detailed Stats Here
More Detailed Stats
52 Members so far, are YOU a member?
Current team score: 1223226 (ranked 374 of 45152)
The CBoard team is doing better than 99.16% of the other teams
Top 5 Members: Xterria(518175), pianorain(118517), Bennet(64957), JaWiB(55610), alphaoide(44374)
Last Updated on: Wed, 30 Aug, 2006 @ 2:30 PM EDT
>shouldn't you be using
I looked again at the first post, and sure enough it said 1 to 5. How I misinterpreted that as "up to 5" is beyond me.
My best code is written with the delete key.