【发布时间】:2021-02-15 16:54:55
【问题描述】:
我对编程很陌生,并且已经开始了 C++ 的在线课程。在课程中,我开始创建一个基本游戏,用户尝试在控制台中猜测一个随机数。我试图将最好的分数存储在一个名为“best_score.txt”的文本文件中。但是,每当我测试我的程序时,我都会在文本文件中不断收到大的负数(例如 -858993460)。我做了很多研究试图解决这个问题,但没有运气,任何帮助将不胜感激,谢谢。这是我的代码:
#include <iostream>
#include <cmath>
#include <float.h>
#include <climits>
#include <string>
#include <istream>
#include <cstdlib>
#include <ctime>
#include <vector>
#include <array>
#include <fstream>
using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::vector;
using std::array;
using std::ifstream;
using std::ofstream;
void print_vector(vector<int> vector)
{
for (int i = 0; i < vector.size(); i++) {
std::cout << vector[i] << "\t";
}
std::cout << '\n';
}
void play_game()
{
vector<int> guesses;
int count = 0;
int random = rand() % 251;
cout << random << endl;
cout << "guess a number: ";
while (true) {
int guess;
cin >> guess;
count++;
guesses.push_back(guess);
if (guess == random) {
cout << "You Win!!!!\n";
break;
}
else if (guess < random) {
cout << "Too low\n";
}
else if (guess > random) {
cout << "Too high\n";
}
}
ifstream input("best_score.txt");
if (!input.is_open()) {
cout << "Unable to read file\n";
return;
}
int best_score;
input >> best_score;
ofstream output("best_score.txt");
if (count < best_score) {
output << count;
}
else {
output << best_score;
}
print_vector(guesses);
}
int main()
{
srand(time(NULL));
int choice;
do {
cout << "0. Quit\n1. Play Game\n";
cin >> choice;
switch (choice) {
case 0:
cout << "BYYEEEE\n";
break;
case 1:
play_game();
break;
}
} while (choice != 0);
}
【问题讨论】:
-
只是您的程序逻辑必须确保您的代码不会溢出整数类型范围。如果由于某些原因你需要非常大的整数,那么有一个库可以扩展整数的大小。
-
这是学习使用调试器并逐行浏览代码的好时机。你会看到值是什么以及在哪里。你不做任何错误检查,所以如果读取到
best_score不起作用,它可能有任何值,可能是一个非常负的值,它会导致它小于count,例如。 -
请修正缩进,它会误导分析破坏。
-
-858993460 == 0xcccccccc,在 MSVC++ 中用于诊断错误。您忘记为变量赋值。
-
将数字转换为十六进制,即0xcccccccc。然后阅读stackoverflow.com/questions/17644418/…,它可能会帮助您找到错误。
标签: c++