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;
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).
#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;
}
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.