Random Numbers

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!
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) 
Thanks so much! Can I generate multiplication, division, addition and subtraction symbols?
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
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
Oh i didnt know what either, thank you for the info disch.
Thanks so much! You guys are awesome! I successfully made my program.
What if I wanted to make the number between 1 and 5 but not choose 0?
int random = (rand() %5) + 1;
Last edited on
Topic archived. No new replies allowed.