Voodoo Doll's Profile
Reputation: 11
Tradesman
- Group:
- Expert
- Active Posts:
- 108 (0.04 per day)
- Joined:
- 24-January 06
- Profile Views:
- 3,141
- Last Active:
Jan 15 2012 07:23 AM- Currently:
- Offline
Previous Fields
- Country:
- US
- OS Preference:
- Windows
- Favorite Browser:
- Chrome
- Favorite Processor:
- Intel
- Favorite Gaming Platform:
- PC
- Your Car:
- Honda
- Dream Kudos:
- 175
Latest Visitors
-
lucky3 
23 Nov 2012 - 08:38 -
codeprada 
30 Mar 2011 - 12:45 -
sandesh ghubde 
19 Mar 2011 - 05:00 -
kaye143 
27 Jan 2011 - 05:49 -
BlueWave 
18 Oct 2010 - 07:07
Posts I've Made
-
In Topic: this is correct to do a random?
Posted 9 Jan 2012
rand() % N will give you a value in the range of 0 to N-1, inclusive. To get a number between any arbitrary minimum and maximum, take the make N the difference of the maximum and minimum, then shift the range by adding the minimum:
#include <stdio.h> #include <stdlib.h> #include <time.h> #define RMIN 10 #define RMAX 30 int main(void) { srand((unsigned)time(NULL)); for (int x = 0; x < 10; x++) { printf("%d\n", rand() % (RMAX - RMIN) + RMIN); } return 0; }
srand() is used to reseed the generator each time the program is run. Otherwise you'll get the same sequence because the default seed is always 1.
If this is really C++, you have more options with the various new random engines and distribution classes. I default to the Mersenne Twister and uniform int distribution instead of C's rand() because it's a much better engine and I don't have to do any mental math to make sure the range formula is right.
#include <functional> #include <iostream> #include <random> #include <ctime> namespace { const int RMIN = 10; const int RMAX = 30; } int main() { using namespace std; auto rgen = bind( uniform_int_distribution<int>(RMIN, RMAX - 1), mt19937(time(nullptr)) ); for (int x = 0; x < 10; x++) { cout << rgen() << '\n'; } }
My Information
- Member Title:
- D.I.C Head
- Age:
- 28 years old
- Birthday:
- May 13, 1985
- Gender:
-
- Location:
- Atlanta, Georgia
- Interests:
- Programming, messing with computers, parties, swimming, reading, video games, and other stuff I can't think of right now. :)
- Years Programming:
- 11
Contact Information
- E-mail:
- Click here to e-mail me
- Website URL:
-
http://
Friends
|
|


Find Topics
Find Posts
View Reputation Given

|
Comments
Voodoo Doll has no profile comments yet. Why not say hello?