在我的C 范围之外产生数字(太大)

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

本文关键字:数字 太大 我的 范围      更新时间:2023-10-16

我决定乐趣尝试制作一个简单的程序,以"以愚蠢的方式模拟二十一点"。基本上是这样做的,除了随机生成的数字太大的事实。我不在乎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;
}

有什么想法?

您在

中使用 int score;
if (score < computerScore) 

score = score + card; 

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

它恰好具有一些垃圾作为内存内容,编译器对您的初始化至零。实际上,使用非命令变量是不确定的行为。在第一次使用之前将其初始化,在定义本身中优选

int score = 0;

此外,还要在警告上进行编译( -Wall -Wextra for g /clang ),因为编译器会很容易警告这些错误。

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

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