My C++ class is now learning about Random Numbers.
My teacher asks the class to write a program for Magic 8 ball.
Me and my partner don't get what we should do.
So I was wondering if anyone knows how to make a code for Magic 8 ball program or hints on how I should use it with random.
I'll try not to give you the answer. Beating your brains out is a part of programming. Before you right any code try to think of what kind of variables you need. What messages to put for the 8 choices and do you want the program to run once or loop. So something like this.
1 2 3 4 5 6 7
//Ask the user if he wants to play
//get a random number between 1-8
// decide how you want to get choice 1-8, you could use an array if else statements or switch
//output the results
//ask the user if he wants to play again
//proceed accordingly
OK, I'll tell you the basics on randomizing numbers although I will not tell you what your program is. I'm telling you mainly because randomization is confusing in C++.
First of all you should include time.h (aka <ctime>). You will also have to include <cstdlib>. Then at the beginning of your main call srand(time(NULL))
srand is the random seed. It must be called to set a seed (hence the name) to pseudorandomize your numbers. To get it to be reasonably random you call it based on the current millisecond count which is reasonably random for most cases.
Then to generate a random number you call rand()
which generates a random number within a wide range.
To trim that down to a desired range of x to y inclusive change the code to: rand() % (y-x) + x
See these pages for more data: http://www.cplusplus.com/reference/clibrary/cstdlib/rand/ http://www.cplusplus.com/reference/clibrary/cstdlib/srand/