生成我的范围之外的数字C ++(太大了)

时间:2015-05-16 19:48:34

标签: c++

我决定尝试制作一个简单的程序,而不仅仅是#34;以愚蠢的方式模拟二十一点。它基本上完成了,除了随机生成的数字太大的事实。我不关心srand / rand的偏见(现在)我只是想让它正常工作。

#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;
}

有什么想法吗?

2 个答案:

答案 0 :(得分:3)

您在

中使用int score;未初始化
if (score < computerScore) 

score = score + card; 

取决于if(play == 0)if(play == 1)条件。

碰巧有一些垃圾作为其内存内容,编译器不会为你初始化为零。实际上,使用未初始化的变量是未定义的行为。在第一次使用之前初始化它,在定义本身中最好,

int score = 0;

此外,编译时会在(-Wall -Wextra为g ++ / clang ++)上发出警告,因为编译器会轻易警告这些错误。

答案 1 :(得分:0)

尝试运行此操作并查看是否存在相同问题。我刚刚添加了一些打印语句来尝试调试它,它停止向我展示真正的大数字..

     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";
                }