I have a few questions about the random function in C++. I’ve finished the assignment (magic 8 ball), but I just don’t have a lot of insight into how this works.
First, you define a variable:
int answer = std::rand() % 10
Random modulo 10, returns the remainder. This is intended to make a random number from 0-9. I understand how the modulo works, but I don’t understand what it’s dividing, and how this can be guaranteed to return a number from 0-9. If the start number is 3,993,826, it won’t return 0-9, so what is it working on?
A little bit later we add the line:
srand(time(NULL));
So my stab is it has something to do with the clock. Also, with this line, why is it placed where it is in the program? At this point the program essentially looks like this:
int main() {
std::cout <<“MAGIC 8 BALL : \n\n”;
srand(time(NULL));
int answer = std::rand() % 20;
std::cout << answer;
}
why is that NULL line above the variable line? Is there a number already “there” or being accessed that needs to be cleared? Also, earlier in the program it was % 10 and with no explanation, it was changed to % 20. Is there any significance there?
Sorry for the bazillions of questions…I don’t want to just blindly continue by rote—I want to know HOW this stuff works. And I’m an idiot, not a math person so use short words and crayons when you answer. I watched a video series on C++ from Giraffe Academy that got me off to an excellent start and I’ve been relying on my knowledge from there so far, but this is the first truly new concept I’ve found so far (not a complaint, that!) and I don’t feel like I’ve gained any insight into how the random function actually works.
thanks very much. leaves appropriate offerings at the Computer Godz altar, bows, leaves