对于我的中期项目我创建一个随机生成数字的程序,并提示用户减去数字并输入他们的答案,同样在代码中,我想跟踪他们当前的分数,但由于某种原因分数没有更新,所有代码都在哪里
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
A:
srand(time(0));
int number1 = rand() % 10;
int number2 = rand() % 10;
int answer;
int correctAnswer;
int score = 0;
if (number1 < number2)
{
int temp = 0;
temp = number2;
number2 = number1;
number1 = temp;
}
system("CLS");
cout << "Current Score: " << score << endl;
cout << "----------------------------------------------------" << endl;
cout << "What is " << number1 << " - " << number2 << " = ";
cin >> answer;
correctAnswer = number1 - number2;
if (answer == correctAnswer)
{
cout << "Good Job!" << endl;
score = score + 1;
system("Pause");
goto A;
}
else
{
cout << "Incorrect. The Correct Answer is " << correctAnswer <<endl;
cout << "Try Again" << endl;
score = (score * 0);
goto A;
}
system("PAUSE");
return 0;
}
答案 0 :(得分:1)
您的GOTO声明会将您发送到您设置得分= 0的程序顶部...这就是您没有看到分数增加的原因。
移动以下行:
int score = 0;
在“A:”标签上方。
答案 1 :(得分:1)
首先要做的事情:不要使用goto。它通常不被认为是良好的做法,可以使您的代码无法维护。其次,您正在goto中初始化变量,因此在打印之前每次传递都设置为0.
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
int score = 0;
A:
srand(time(0));
int number1 = rand() % 10;
int number2 = rand() % 10;
int answer;
int correctAnswer;
if (number1 < number2)
{
int temp = 0;
temp = number2;
number2 = number1;
number1 = temp;
}
system("CLS");
cout << "Current Score: " << score << endl;
cout << "----------------------------------------------------" << endl;
cout << "What is " << number1 << " - " << number2 << " = ";
cin >> answer;
correctAnswer = number1 - number2;
if (answer == correctAnswer)
{
cout << "Good Job!" << endl;
score = score + 1;
system("Pause");
goto A;
}
else
{
cout << "Incorrect. The Correct Answer is " << correctAnswer <<endl;
cout << "Try Again" << endl;
score = (score * 0);
goto A;
}
system("PAUSE");
return 0;
}