2

当谈到 C++ 时,我是一个初学者。

我必须编写一个提出问题的程序,然后我给出答案,而不是检查它是对还是错。

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

class Question
{
public:
       Question();

       void set_text(string question_text);
       void set_answer(string correct_response);
       bool check_answer(string response) const;
       void display() const;

private:
        string text;
        string answer;
};

Question::Question()
{
}    

void Question::set_text(string question_text)
{
     text = question_text;
}

void Question::set_answer(string correct_response)
{
     answer = correct_response;
}

bool Question::check_answer(string response) const
{
     return response == answer;    
}

void Question::display() const
{
     cout << text << endl;
}

int main()
{
    string response;
    cout << boolalpha;

    Question q1;
    q1.set_text("Who was the inventor of  C ++ ? " );
    q1.set_answer("Bjarne Stroustrup" );

    q1.display();
    cout << " Your answer is :  " ;
    getline(cin,response);
    cout << q1.check_answer(response) << endl;
    return 0;
}

问题是我还需要为 NumericalQuestion 添加一个类,以检查响应和预期答案之间是否存在超过 0.01 的差异。这就是我遇到困难的地方。如果有人可以告诉我如何完成或给我一些提示,我将非常感激。

4

1 回答 1

1

我不会写完整的代码,因为它看起来像我的作业。假设您有一个名为NumericalQuestion. 现在,由于您要使用小数点数字,因此answer变量的类型需要float(或double)。在这种情况下,您需要将从控制台读取的字符串转换为浮点数并将其设置为该对象作为预期响应。用户输入答案后,您需要再次将其转换为float并调用check_answer. 在里面check_answer你需要比较答案和预期答案之间的差异是否小于 0.01。您可以通过这样做来实现这一点return fabs(answer - response) < 0.01

于 2012-04-23T12:40:01.930 回答