Rand number gen help

Hey i have been playing around with random num gens and have had some issues.
First of all i keep getting a the same string of numbers(i have even tried srand).
And second of all i have had an issue with this switch statement it prints out everything passed the number it gets.

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
#include <stdlib.h>
#include <ctime>

using namespace std;

int random_integer;

int random();

int main()
{
    random();

    cout << random_integer;

    switch(random_integer)
    {

        case 1 : cout << "You got a flying lizard!";

        case 2 : cout << "You got a wolf!";

        case 3 : cout << "You got a mutant bunny!";

        case 4 : cout << "You got a rock monster!";

        case 5 : cout << "You got a loyal dog!";

        case 6 : cout << "You got a large mole!";

        case 7 : cout << "You got a snapping turtle!";

        case 8 : cout << "You got a kangaroo!";

        case 9 : cout << "You got a lion!";

    }
    
    return 0;

}


int random()
{
    srand(clock());

    random_integer = rand()%10;
    
    return 0;

}
1) Don't call srand() every time you want a number. You should call it exactly once at the start of main. rand() is ok to call multiple times.

2) case blocks in a switch need to end with a break; statement or else code will "bleed through" to the next case.


EDIT:

Also... generally time is used to seed srand... not clock:

srand( (unsigned)time(nullptr) );

This might be why you're getting the same number every time.



Also.... it would make more sense for random() to actually return the random number, rather than set a global and return 0. That way you don't need to make random_integer global at all:

1
2
3
4
5
6
7
8
9
10
11
12
13
int main()
{
    int random_number;  // no longer needs to be global.  Globals are bad - avoid them.

    random_number = random();  // grab the return value

    //...
}

int random()
{
    return rand() % 10;  // <- return the value, rather than returning 0
}
Last edited on
Call srand() only once instead of every time you get a random number.
Thanks for the help!
Topic archived. No new replies allowed.