我这里有一个程序,使用两个随机生成的数字随机运行加法或减法。然后用户必须输入答案,如果正确,则表示“正确”,如果错误则表示“不正确”并显示正确的答案。似乎当我运行我的代码时它没有显示正确的答案,而是它认为正确的错误答案。例如,我运行代码,我得到的问题是950 + 921。答案应该是1871但它告诉我我不正确,对程序的正确答案是1042.我不知道错误在哪里我的代码,但在这里,如果你想看看:
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <ctime>
using namespace std;
int main()
{
srand(static_cast<unsigned int>(time(NULL)));
cout << "Welcome to the Math Tutor!" << endl;
int N1 = rand() % 999;
int N2 = rand() % 100;
int symbol = rand() % 2;
int Result;
int Answer;
cout << setw(5) << N1 << endl;
if(symbol == 1)
{
cout << "+";
Result = N1 + N2;
}
else
{
cout << "-";
Result = N1 - N2;
}
cout << setw(3) << N2 << symbol << "\n";
cout << setw(5) << "------\n\n";
cout << "Enter your answer: ";
cin >> Answer;
if(Answer == Result)
{
cout << "You are correct!\n\n";
}
else
{
cout << "You are incorrect, the correct answer is: " << Result << "\n\n";
}
cin.ignore(1);
return 0;
}
答案 0 :(得分:1)
您从symbol
之后输出N2
,从这一行开始:
cout << setw(3) << N2 << symbol << "\n";
因此实际计算不是950 + 921
950 + 92
1042
。
要解决此问题,请不要输出symbol
,如下所示:
cout << setw(3) << N2 << "\n";