Equation(类与对象+构造)

目录

题目描述

AC代码

思路分析


题目描述

建立一个类Equation,表达方程ax2+bx+c=0。类中至少包含以下方法:

1、无参构造(abc默认值为1、1、0)与有参构造函数,用于初始化a、b、c的值;

2、set方法,用于修改a、b、c的值

3、getRoot方法,求出方程的根。

一元二次方程的求根公式如下:

一元二次方程的求解分三种情况,如下:

输入

输入测试数据的组数t

第一组a、b、c

第二组a、b、c

输出

输出方程的根,结果到小数点后2位

在C++中,输出指定精度的参考代码如下:

#include <iostream>

#include <iomanip> //必须包含这个头文件

using namespace std;

void main( )

{ double a =3.141596;

cout<<fixed<<setprecision(3)<<a<<endl;  //输出小数点后3位

输入样例1 

3
2 4 2
2 2 2
2 8 2

输出样例1

x1=x2=-1.00
x1=-0.50+0.87i x2=-0.50-0.87i
x1=-0.27 x2=-3.73

AC代码

#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
class Equation {
		double a, b, c;
	public:
		Equation() {
			a = b = c = 1;
		}
		Equation(float a, float b, float c): a(a), b(b), c(c) {}
		void setabc(float a, float b, float c) {
			this->a = a;
			this->b = b;
			this->c = c;
		}
		void getRoot() {
			float judge = b * b - 4 * a * c,x1,x2,r,i;
			cout<<fixed<<setprecision(2);
			if (judge > 0) {
				x1=(-b + sqrt(judge)) / (2 * a);
				x2=(-b - sqrt(judge)) / (2 * a);
				cout.precision(2);
				cout << "x1=" << x1;
				cout.precision(2);
				cout << " x2=" << x2<< endl;
			} else if (judge == 0) {
				cout.precision(2);
				x1=-b / (2 * a);
				cout<< "x1=x2=" << x1 << endl;
			} else {
				r=-b/(2*a);
				i=sqrt(-judge)/(2*a);
				cout.precision(2);
				cout << "x1=" << r<<'+'<<i;
				cout.precision(2);
				cout << "i x2=" << r<<-i<< 'i' << endl;
			}
		}
};
int main() {
	double t, a, b, c;
	cin >> t;
	while (t--) {
		cin >> a >> b >> c;
		Equation equation(a, b, c);
		equation.getRoot();
	}
}

思路分析

主要是格式控制问题,隔了几个月,有点忘记了,想用成员函数cout流的格式控制,一开始用的是cout.precision(2),后来发现这个只能控制位宽,还是用cout<<fixed<<setprecision(2)吧。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MaolinYe(叶茂林)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值