Xcode C++程序结果未显示正确答案

Xcode C++ Program result not displaying correct answer

本文关键字:答案 显示 C++ 程序 结果 Xcode      更新时间:2023-10-16

我这里有一个程序,它使用两个随机生成的数字随机运行加法或减法。然后,用户必须输入答案,如果正确,则说"正确",如果错误,则说"不正确"并显示正确答案。当我运行代码时,它似乎没有显示正确的答案,而是它认为正确的错误答案。例如,我运行代码,我遇到的问题是 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) << "------nn";
    cout << "Enter your answer: ";
    cin >> Answer;
    if(Answer == Result)
    {
        cout << "You are correct!nn";
    }
    else
    {
        cout << "You are incorrect, the correct answer is: " << Result << "nn";
    }
    cin.ignore(1);
    return 0;
}

你在 N2 之后输出symbol ,从这一行:

cout << setw(3) << N2 << symbol << "n";

因此,实际计算不是950 + 921而是950 + 92 1042

要解决此问题,请不要输出symbol,如下所示:

cout << setw(3) << N2 << "n";