Random Numbers

Sep 28, 2012 at 9:50pm
I am developing a program that will generate algebra problems and answers for me to use for studding at home. I need to make some random numbers but every time I try, I only get the same number every time I press refresh. How can I generate random numbers?

Thanks!
Sep 28, 2012 at 9:51pm
1
2
3
4
5
6
7
8
9
#include <cstdlib>
#include <ctime>


// do this once at the start of main:
srand( (unsigned)time(0) );

// do this when you want a random number:
int num = rand() % 10;  // generates a number between [0..10) 
Sep 28, 2012 at 10:20pm
Thanks so much! Can I generate multiplication, division, addition and subtraction symbols?
Sep 28, 2012 at 10:34pm
I'm guessing you were using srand( time_t (0) ), if so don't, next time, just make it srand( (unsigned)time(0) );.

What do you mean can you generate the symbols. Do you mean using the random function?

If you do mean can you generate the symbols using random function, then my answer to that is no, atleast not to my knowledge.
Last edited on Sep 28, 2012 at 10:40pm
Sep 28, 2012 at 10:50pm
You can only generate numbers with rand. However you can use those numbers to generate symbols with a common technique called a "lookup table"

1
2
3
4
const char symbollookup[4] = {'+', '-', '*', '/'};

// pick a random one of those four symbols
char randomsymbol = symbollookup[ rand() % 4 ];
Last edited on Sep 28, 2012 at 10:51pm
Sep 28, 2012 at 10:58pm
Oh i didnt know what either, thank you for the info disch.
Sep 28, 2012 at 11:25pm
Thanks so much! You guys are awesome! I successfully made my program.
Sep 29, 2012 at 12:17am
What if I wanted to make the number between 1 and 5 but not choose 0?
Sep 29, 2012 at 12:28am
int random = (rand() %5) + 1;
Last edited on Sep 29, 2012 at 12:28am
Topic archived. No new replies allowed.