Cody Hayes
Cody Hayes

Reputation: 49

Generating numbers outside of my range C++ (way too large)

I decided for fun to try and make a simple program that "sort of" simulates blackjack in a dumbed down way. It's basically done, except for the fact that the randomly generated numbers are WAY too large. I don't care about the bias srand/rand has (for now) I just want to get it working properly.

#include <iostream>
#include <cstdlib>
#include <cmath>
#include <ctime>

using namespace std;

int genRandInt (int low, int high) {
    int randnum = low + (rand() % (high - low + 1));
    return randnum;
}

int main()
{
    srand(time(NULL));
    int computerScore;
    int score;
    int card;

    while (int playAgain = 1)
    {
        cout << "Enter 0 to hold or 1 to hit: ";
        int play;
        cin >> play;

        if (play == 0)
        {
             computerScore = genRandInt(1, 31);

             if (score < computerScore)
             {
                 cout << "Your score is " << score << " and the computer's score is " << computerScore << "! You lose.\n";
             }

             if (score > 21)
             {
                 cout << "Your score is " << score << " which is greater than 21. Bust!\n";
             }

             if (score > computerScore && score <= 21)
             {
                 cout << "Your score is " << score << " and the computer's score is " << computerScore << "! You win!\n";
             }

             cout << "Would you like to play again? 1 for yes, 0 for no. : ";
             cin >> playAgain;
        }


        if (play == 1)
        {
            card = genRandInt(1, 11);
            score = score + card;
            cout << "Your score is: " << score << "\n";
        }
    }



    return 0;
}

Any ideas?

Upvotes: 2

Views: 67

Answers (2)

vsoftco
vsoftco

Reputation: 56567

You use int score; uninitialized in

if (score < computerScore) 

or

score = score + card; 

depending on the if(play == 0) or if(play == 1) condition.

It happens to have some junk as its memory content, the compiler does not initializes to zero for you. In fact, it is undefined behaviour to use un-initialized variables. Initialize it before the first usage, preferable in the definition itself,

int score = 0;

Also, compile with warnings on (-Wall -Wextra for g++/clang++), since the compiler will easily warn about these mistakes.

Upvotes: 3

jordanbana
jordanbana

Reputation: 97

Try running this and seeing if you have the same issues. I just added some print statements to try and debug it, and it stopped showing me really big numbers..

     EDIT:
//ADD
    int score = 0;
//

                if (play == 1)
                {
                    cout << "printing in the PLAY = 1 "<< score << endl;
                    card = genRandInt(1, 11);
                    score = score + card;
                    cout << "Your score is: " << score << "\n";
                }

Upvotes: 0

Related Questions