Hey im trying to make a function that you can pass two values to, a RANGE_MIN and a RANGE_MAX, than generate and return a random number between those two numbers.

My first section of code repeats the same number every time i run the program (unless i change something and recompile)

#include <iostream>
#include <stdlib.h> 
#include <time.h>
using namespace std;

int getRand()
{ 
    srand( (unsigned)time( NULL ) );
    int RANGE_MIN = 0;
    int RANGE_MAX = 100;
    int myRand = (((double) rand() / 
                         (double) RAND_MAX) * RANGE_MAX + RANGE_MIN);

    return myRand;
}

int main(){
    cout << getRand();
    cin.ignore(2);
}

and if i slightly modify that code and remove the calculations from the myRand integer and simply replace the calculations (((double) rand() / (double) RAND_MAX) * RANGE_MAX + RANGE_MIN); with rand(); i am fine.

So it must have something to do with my double types losing precision or something like that?

EDIT: I figured out a much easier way of calculating a rand num that didnt involve all the typecasting (rand()%RANGE_MAX)+RANGE_MIN;

Recommended Answers

All 2 Replies

use srand() to see the random number generator

int main(){
   srand(time(0));
    cout << getRand();
    cin.ignore(2);
}

He did use srand actually...

The problem, Woobag, is that you're only supposed to seed the random number generator once. If you seed it every time you run rand, then you're resetting the random number generator back to its original state each time! So use srand once - as Ancient Dragon shows.

EDIT: I figured out a much easier way of calculating a rand num that didnt involve all the typecasting (rand()%RANGE_MAX)+RANGE_MIN;

Use the method you were working with previously. The random number generator will not be as 'random' if you scale your values with this method. This depends on the random number algorithm rand uses, but common implementations work better with the other method.

Oh, and it would be (rand() % (RANGE_MAX - RANGE_MIN)) + RANGE_MIN and likewise ((double) rand() / (double) RAND_MAX) * (RANGE_MAX - RANGE_MIN) + RANGE_MIN. Your code works fine, though, as long as RANGE_MIN is zero...

I am hoping you are trying to generate a number that is greater than or equal to RANGE_MIN and (strictly) less than RANGE_MAX.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.