【问题标题】:Xcode C++ Program result not displaying correct answerXcode C++ 程序结果未显示正确答案
【发布时间】:2016-07-13 18:14:35
【问题描述】:

我这里有一个程序,它使用两个随机生成的数字随机运行加法或减法。然后用户必须输入答案,如果正确则显示“正确”,如果错误则显示“不正确”并显示正确答案。当我运行我的代码时,它似乎没有显示正确的答案,而是它认为正确的错误答案。例如,我运行代码,我得到的问题是 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;

}

【问题讨论】:

    标签: c++ xcode random output


    【解决方案1】:

    您在N2 之后输出symbol,来自这一行:

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

    因此,实际计算的不是950 + 921,而是950 + 921042

    要解决这个问题,不要像这样输出symbol

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

    【讨论】:

    • 这样分解才有意义!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多