Random number help

I am trying to have it generate a random number between 1-100. but it shows 51 every time. is there any reason for this?

I included <cstdlib> at the top.

1
2
3
inline int rand_func(){
       return (rand()%100+10);
}     
You're either calling srand more than once or less than once.
http://www.cplusplus.com/reference/clibrary/cstdlib/srand/
or you're doing something like this:

1
2
3
int r = rand_func();
for(int i = 0; i < 100; ++i)
  cout << r << endl;  // prints the same number every time because 'r' never changes 
heres more of the code maybe this will give somebody a better idea of what im doing wrong. the random number is always 51..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>                                                                                         //headers
#include <cstdio>
#include <cstdlib>
using namespace std;

enum choose{CarWash=1,SuperCarWash,SuperDooperCarWash,Quit};

inline int rand_func();
int display_menu();
int big_switch(int);

int random;

int main(){

    bool valid;
    
    cout<<rand_func();
    do{
       display_menu();
       valid=big_switch(random);
    }while(!valid);
    
    system("pause");
}

inline int rand_func(){
       return (rand()%100+10);
}     
you never set 'random' to anything.
but shouldn't it still randomize ?
'random' is just a variable. Naming it 'random' doesn't actually make it random. You might as well name it 'popscicle'. The name makes no difference. What matters is what you do with it.

Your 'rand_func' function actually does produce a random number. But you're only calling it once in main.

Also, like Athar said, you never call srand (which you need to do to seed rand), which would explain why it prints the same thing every time.

Call srand once and only once when main starts:

1
2
3
4
5
6
int main()
{
    srand( (unsigned)time(0) );  // call srand once with the time

    // now rand is properly seeded and will produce difference sequences each time the program
    //   is run 
If your code is windows only call rand_s() instead,
why? what's insecure about rand?

Don't make your code nonstandard unless you have a good reason to.
Topic archived. No new replies allowed.