我决定尝试制作一个简单的程序,以“笨拙”的方式模拟二十一点。除了随机生成的数字太大以外,基本上已经完成了。我不关心rand / 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;
另外,请在上加上警告(对于g++ / clang++为
-Wall -Wextra
)进行编译,因为编译器很容易就这些错误发出警告。