Voodoo Doll's Profile User Rating: -----

Reputation: 11 Tradesman
Group:
Expert
Active Posts:
108 (0.04 per day)
Joined:
24-January 06
Profile Views:
3,141
Last Active:
User is offline 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

Icon   Voodoo Doll has not set their status

Posts I've Made

  1. 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. :D
    #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:
Website URL  http://

Friends

Comments

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