在我的C 范围之外产生数字(太大)
Generating numbers outside of my range C++ (way too large)
我决定乐趣尝试制作一个简单的程序,以"以愚蠢的方式模拟二十一点"。基本上是这样做的,除了随机生成的数字太大的事实。我不在乎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";
}
相关文章:
- 当我的阵列太大时出现分段错误
- 为什么C++程序在太大时返回代码而不是答案?
- googletest:测试太大的数据结构
- 整数文本太大,无法用任何整数类型表示--C++
- C++ boost::multi_array索引太大
- 使用 MinGW 构建 ASSIMP 会导致文件太大错误
- 与WM_DPICHANGED消息一起发送的建议窗口大小太大
- 在 Cygwin G++ 上编译的文件太大
- iOS:添加静态库后C++应用大小太大
- 可以将数字的大括号列表用作传递给可变参数函数(或构造函数)的参数吗?
- 当小部件太大时,Gtk 3
- 将字符转换为ASCII返回数字太大
- 为什么此范围基于语句返回一个数字太低的范围
- 这个查找查询是否出错,因为我输入的数字太大
- 词频程序 - 文件输入太大?
- 将 32 位浮点数和不强制转换的 32 位整数与双精度进行比较,当其中一个值可能太大而无法完全适合另一种类型时
- 一个倒梯形,但如果输入高度对于宽度来说太大,那么它应该报告,不可能("不可能的形状"是什么)
- 我如何减去同等数字的大数字
- Pollard Rho 在不太大的输入上崩溃
- 在我的C 范围之外产生数字(太大)