gpt4 book ai didi

C++//数值问题

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:32:35 25 4
gpt4 key购买 nike

我是 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。这就是我遇到困难的地方。如果有人可以告诉我如何做到这一点或给我一些提示,我将非常感激。

最佳答案

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

关于C++//数值问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10280467/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com