Function question

Hello. I have started to work through some C++ books and can't get functions to work the way I think they should. Can someone point me at an explanation or a solution for me to reverse engineer to build an understanding.

I want this to generate 3 random 1-5 numbers. It generates the random number then continues to use the same number for the entire program. How do I make the D5() function run each time to get a new number each time?

Thanks


int D5()
{
int magic, guess , counter, numberD5;
srand(time(NULL));
magic=rand();

numberD5=(rand()%10+1)/2;
return (numberD5);
}
int main()
{

cout << "test random generator " << D5() << endl;
cout << "test random generator " << D5() << endl;
cout << "test random generator " << D5() << endl;

system ("PAUSE");
return 0;
}
closed account (4z0M4iN6)
If you always start with time(NULL), you always will get the same value.

You should do it this way:

http://www.cplusplus.com/reference/clibrary/cstdlib/srand/

I suggest, you make a static variable and use this as a counter for increasing srand values.
You initialize the value with 0 (static initialization). And for 0 (if), you use time(NULL).
closed account (1vRz3TCk)
I would suggest only using srand() once at the start of your main.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <time.h>

int D5()
{
    return ((rand() % 5 + 1));
}

int main()
{
    srand( static_cast<unsigned>( time(NULL) ) );  
    // Don't worry to much about static_cast at the moment
    // it just converts the type retuned from time() to
    // the type expecteced by srand(). if you don't do it
    // you get a warning.
    
    std::cout << "test random generator " << D5() << std::endl;
    std::cout << "test random generator " << D5() << std::endl;
    std::cout << "test random generator " << D5() << std::endl;

    system ("PAUSE");

    return 0;
}
Last edited on
Notice how CodeMonkey wrote his rand() statement: (rand() % 5 + 1). Compare this to your rand() statement: (rand()%10+1)/2.

Your statement does not provide your stated intended purpose.

The rand() function returns an int between 0 and RANDMAX. When you take the modulo (% 10), you get a (pseudo-)random number between 0 and 9 (inclusive). By adding 1, you change this range to [1, 10]. Then you divide by 2. This will give you the value 0 10% of the time, 5 10% of the time and 1, 2, 3 and 4 each 20% of the time.

CodeMonkey, on the other hand, did a modulo 5 (% 5), which yields a random number between 0 and 4, inclusive. Adding 1 to the result yields the desired random distribution between 1 and 5.
Topic archived. No new replies allowed.