Questions about code and random function.

I just had some random questions about C++ coding I've been thinking about.

For the variable won, if it isn't set to 0, a logic error occurs when total is printed when the program is ran because without it being initialized to zero an indeterminate value shows. I corrected this error awhile back when I wrote the program, but I never quite figured out why it was set to an indeterminate value.

won=0 was originally just won.

I thought this was okay because I had won being set--depending on if the user got three images or two images correct--to won=(money*'three or two for cal').

I don't understand why that didn't get rid of the garbage number won was originally set at and replaced with the number created by won=(money*'three or two for cal').

I felt like it should've automatically got rid of the garbage value, and from there, as the user kept playing, total would just count up all the won values each time the user won with two or three images. Can someone explain the error in my reasoning?



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
{
    double won=0;

    if(slot1==slot2 || slot1==slot3 || slot2==slot3)
    {
        cout << "Congratulations! You won." << endl;
        won=(money * TWO_FOR_CAL);
        cout << "You won " << won << endl;
    }//end of if statement


    else if ((slot1==slot2 && slot1==slot3) || (slot2==slot1 && slot2==slot3) || (slot3==slot1 && slot3==slot2))
    {
        cout << "Congratulations! You won." << endl;
        won=(money*THREE_FOR_CAL);
        cout << "You won " << won << endl;
    }//end f else if
    else
    {
        cout << "You didn't earn any money." << endl;
    }//end of else

    total=(total+won);
}//end calculateAmountEarnedByPlaying 




The other questions I have concern the randomized function.

I figured out that srand(time(0)); should only be done once outside and before your loop, and not repeatedly done in the loop, but I could've figure out why.

I just know when I placed it outside of the do-while loop, it worked. Can someone explain why it formed a logic error when I put srand(time(0)); inside the loop, and why it's supposed to be outside?




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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
#include <stdlib.h>
using namespace std;

void switchStatementsCalculations (int &slot1, int &slot2, int &slot3, string cherries, string
                                   oranges, string plums, string bells, string melons, string bars);

void calculateAmountEarnedByPlaying (double &money, int slot1, int slot2, int slot3,
                                     double &total);

int main()
{
    int slot1;
    int slot2;
    int slot3;

    double money=0;
    double total=0;
    double amountOfMoneyEnterd=0;
    int count;

    string cherries = "cherries";
    string oranges = "oranges";
    string plums = "plums";
    string bells = "bells";
    string melons = "melons";
    string bars = "bars";
    string doAgain;

    cout << "We are going to be playing a slot machine game today." << endl;
    srand(time(0));

    do
    {

        cout << "Please enter the amount of money you'd like to insert into the slot machine. We will pull the lever for you." << endl;
        cin >> money;
        cout << "You put in $" << money << endl;




        slot1=rand()%6+1;
        slot2=rand()%6+1;
        slot3=rand()%6+1;

        switchStatementsCalculations(slot1, slot2, slot3, cherries, oranges, plums, bells, melons, bars);

        calculateAmountEarnedByPlaying(money, slot1, slot2, slot3, total);

        amountOfMoneyEnterd=(amountOfMoneyEnterd+money);





        cout << "Would you like to play again? Please type yes if so." << endl;
        cin >> doAgain;
        if(doAgain!= "yes")
        {
            cout << "The total amount of money you put in the slot machine is " << amountOfMoneyEnterd << endl;
            cout << "The total amount of money you won is $" << total << endl;
        }

    }
    while(doAgain=="yes");


    system("Pause");
    return 0;
}

void switchStatementsCalculations(int &slot1, int &slot2, int &slot3, string cherries, string
                                  oranges, string plums, string bells, string melons, string bars)
{
    switch (slot1)
    {
    case 1:
        cout << "You got " << cherries << endl;
    case 2:
        cout << "You got " << oranges << endl;
        break;
    case 3:
        cout << "You got " << plums << endl;
        break;
    case 4:
        cout << "You got " << bells << endl;
        break;
    case 5:
        cout << "You got " << melons << endl;
        break;
    case 6:
        cout << "You got " << bars << endl;
    }

    switch (slot2)
    {
    case 1:
        cout << "You got " << cherries << endl;
        break;
    case 2:
        cout << "You got " << oranges << endl;
        break;
    case 3:
        cout << "You got " << plums << endl;
        break;
    case 4:
        cout << "You got " << bells << endl;
        break;
    case 5:
        cout << "You got " << melons << endl;
        break;
    case 6:
        cout << "You got " << bars << endl;

    }

    switch (slot3)
    {
    case 1:
        cout << "You got " << cherries << endl;
        break;
    case 2:
        cout << "You got " << oranges << endl;
        break;
    case 3:
        cout << "You got " << plums << endl;
        break;
    case 4:
        cout << "You got " << bells << endl;
        break;
    case 5:
        cout << "You got " << melons << endl;
        break;
    case 6:
        cout << "You got " << bars << endl;

    }
}

void calculateAmountEarnedByPlaying(double &money, int slot1, int slot2, int slot3, double &total)

{
    double won=0;

    if(slot1==slot2 || slot1==slot3 || slot2==slot3)
    {
        cout << "Congratulations! You won." << endl;
        won=(money * 2);
        cout << "You won " << won << endl;
    }


    else if ((slot1==slot2 && slot1==slot3) || (slot2==slot1 && slot2==slot3) || (slot3==slot1 && slot3==slot2))
    {
        cout << "Congratulations! You won." << endl;
        won=(money*3);
        cout << "You won " << won << endl;
    }
    else
    {
        cout << "You didn't earn any money." << endl;
    }

    total=(total+won);
}


Last edited on
As for the others, they aren't related to my code, but rather my confusion.


http://prntscr.com/bquxs9

"The C++library provides a value-returning function named rand()that returns a random number.(The rand()function requires the directive #include <cstdlib>). The random number that is returned from the rand() function is an int. Here is an example of its usage:y = rand();After this statement executes, the variable will contain a random number."

I understand this part.


"The function uses an algorithm that produces the same sequence of numbers each time the program is repeated on the same system. For example, suppose the following statements are executed."
cout << rand() << endl;
cout << rand() << endl;
cout << rand() << endl;

The three numbers displayed will appear to be random, but each time the program runs,the same three values will be generated. In order to randomize the results of rand()."

What do they mean by the same system?
And why without srand() does rand() do this? It never explained why; it just said we need srand to make it random each time the program executes.

"The srand()function accepts an unsigned int argument, which acts as a seed value for the algorithm."

What's an unsigned argument and a seed value, and by the value acting as a seed value for the algorithm, do they mean they changing the algorithm inside the rand() function so that it produces different numbers each time a program is executed or does it change the algorithm inside the srand function?

"By specifying different seed values, rand()will generatedifferent sequences of random numbers."

But I still don't understand how this is related to srand()? Srand() produces a value that's somehow transported to each rand() statement so that each time the program is ran it executes different values because srand() changed the algorithm in rand()? Even so, how is it that without srand(), rand() makes the program print the same random numbers each time it's executed?

Is each specific rand() stored in the computer's memory in a way when it's executed it just shows those values, where when you add srand() it randomizes that value in the memory each time?


"A common practice for getting unique seed values is to call the time()function, which is part of the C++ standard library. The time()function returns the number of seconds that have elapsed since midnight, January 1, 1970. The time()function requires the directive #include <ctime>. When you call the time()function,you pass 0 as an argument."



http://prntscr.com/bqv6ug

Getting the system time makes sense, but I'm still having trouble understanding what an unsigned seed is or what a seed value is in general, thus I don't understand the step under it that says //seed the random number generator.

The image is also different from what I used in my slotmachine program, so I'm a bit off.


srand(time(0));

Why do we have to put time(0) even? Why not just time since it's going to give us a random number? I know when we call it that is passed 0 as an argument, but why is this necessary?

http://prntscr.com/bqvapz

How does 1+rand()%100=1-100?

If the random number was 99 why isn't it 99-100.

How does getting a remainder of a number=1-100.

I get why they have to add one in case rand() gets a number that goes into 100 evenly, but how all this is limiting the range of the random number and making it so that we can get a number between 1 and a 100 confuses me.




Last edited on
For the variable won, if it isn't set to 0, a logic error occurs when total is printed when the program is ran because without it being initialized to zero an indeterminate value shows...


If all slot values are different from each other won will not be set and that is a problem when you try to use it to calculate the total.


I figured out that srand(time(0)); should only be done once outside and before your loop, and not repeatedly done in the loop, but I could've figure out why...


The rand() function works by having some internal state (this can be as simple as a single int value). When it is called it uses its internal state to produce a number (often called pseudorandom number because it's not truly random) and then updates the state so that a different number will be generated next time the function is called.

The srand() function is used to initialize the internal state that the rand() function uses. This is called seeding (srand = seed rand). If you use a different seed you get a different sequence of numbers from rand(). That's why time(0) is often used as a seed.

One of the most obvious problems with using time(0) as a seed is that it returns the current time in seconds. If you call srand(time(0)) before each call to rand() that means all random numbers that are generated within the same second will be the same.

https://en.wikipedia.org/wiki/Linear_congruential_generator
What do they mean by the same system?


In this situation I think they mean the implementation of rand().
The C++ standard doesn't specify exactly how rand() should work so it is possible that it can differ depending on what operating system or compiler you're using.


why without srand() does rand() do this? It never explained why; it just said we need srand to make it random each time the program executes.


Computers are good at calculating things in a predictable manner. Using a predictable method to generate something that appear random is not an easy task but that's what rand() has to do.

If you don't use srand() it means rand() will always start out from the same initial state and because the method used is totally predictable it will always give you the same numbers.


What's an unsigned argument and a seed value, and by the value acting as a seed value for the algorithm, do they mean they changing the algorithm inside the rand() function so that it produces different numbers each time a program is executed or does it change the algorithm inside the srand function?


Unsigned means the value can not have negative sign. If you pass a negative value it will automatically be converted to an unsigned value so you don't need to worry too much about the value being unsigned in this particular situation.

The seed value is the value that you pass to srand(). The algorithm doesn't change. It's just the input to the random number generator that changes.


Is each specific rand() stored in the computer's memory in a way when it's executed it just shows those values, where when you add srand() it randomizes that value in the memory each time?


You could think of it that way (even though in reality the values are probably calculated on the fly). Calling rand() repeatedly gives you a sequence of random numbers. Eventually, after calling rand() many times, you start getting the same sequence of numbers again. This is often refereed to as the period.

The period depends on the implementation. To make things simple lets pretend for this example that the period is 4 (in reality it's much bigger) and that the first 4 calls to rand() gives the values 8, 3, 5 and 1.
1st call to rand() => 8   8 3 5 1
                          ^

2nd call to rand() => 3   8 3 5 1
                            ^

3rd call to rand() => 5   8 3 5 1
                              ^

4th call to rand() => 1   8 3 5 1
                                ^

On the next call to rand() the sequence will start to repeating.
5th call to rand() => 8   8 3 5 1
                          ^

6th call to rand() => 3   8 3 5 1
                            ^

...

By calling srand you can set a different starting position for the sequence. You can't know exactly what you will set it but you know that using two different seeds will probably give you different positions within the sequence. For this example lets pretend you call srand() with some arbitrary number that makes the sequence starting from number 5.
1st call to rand() => 5   8 3 5 1
                              ^

2nd call to rand() => 1   8 3 5 1
                                ^

3rd call to rand() => 8   8 3 5 1
                          ^

4th call to rand() => 3   8 3 5 1
                            ^

In reality the period is often much bigger so you probably will never experience the numbers repeating.


Why do we have to put time(0) even? Why not just time since it's going to give us a random number? I know when we call it that is passed 0 as an argument, but why is this necessary?

The 0 that is passed to the time() function is actually a null pointer constant. If you look at the documentation for time() you see that it takes a pointer to a time_t object as argument. It allows you to do things like:
1
2
3
time_t t;
time(&t);
srand(t);

I don't really understand why they did it this way because the time() function already returns a time_t object so you could just as well do:
1
2
time_t t = time(0);
srand(t);

For our purposes we only want to use the time for one thing so using a time_t variable is unnecessary.
 
srand(time(0));

http://www.cplusplus.com/reference/ctime/time/


I get why they have to add one in case rand() gets a number that goes into 100 evenly, but how all this is limiting the range of the random number and making it so that we can get a number between 1 and a 100 confuses me.


rand() % 100 calculates the remainder of the integer division rand() / 100. https://en.wikipedia.org/wiki/Remainder
The remainder of a division with 100 gives you a value from 0-99.
Adding one to this number means you get a value from 1-100.
Last edited on
"If all slot values are different from each other won will not be set and that is a problem when you try to use it to calculate the total."

Could you explain this part more? Also, thanks for replying to such a long thread! <3
I mean if none of slot1, slot2 and slot3 are the same then the last else will run.
1
2
3
4
    else
    {
        cout << "You didn't earn any money." << endl;
    }

As you can see it doesn't set the won variable so if won has not already been initialized it will still be uninitialized on the line below.
 
    total=(total+won);

This is a problem because, as you said, won will contain a "garbage value".
Last edited on
Topic archived. No new replies allowed.