学堂在线 c++基础 之 C4-3 一元二次方程求解

题目描述

对于一元二次方程ax^2 + bx + c = 0,解可以分为很多情况。

若该方程有两个不相等实根,首先输出1,换行,然后从小到大输出两个实根,换行;

若该方程有两个相等实根,首先输出2,换行,然后输出这个这个实根,换行;

若该方程有一对共轭复根,输出3,换行;

若该方程有无解,输出4,换行;

若该方程有无穷个解,输出5,换行;

若该方程只有一个根,首先输出6,换行,然后输出这个跟,换行;

要求使用c++ class编写程序。可以创建如下class

#include <iostream>
#include <cmath>
using namespace std;
class Equation{
private:
    int _a, _b, _c;
public:
    Equation(int a, int b, int c){
    }
    void solve(){
    }
};
int main(){
    int a, b, c;
    cin >> a >> b >> c;
    Equation tmp(a, b, c);
    tmp.solve();
    return 0;
}


 

 

输入描述

该一元二次方程的系数a,b,c,且-100=<a,b,c<=100

输出描述

解的情况。输出解的时候保留两位小数

样例输入

 

1 4 3

样例输出

1
-3.00 -1.00

 

#include <iostream>
#include<cmath>
#include <cstdio>
using namespace std;
class Equation {
private:
	int _a, _b, _c;
public:
	Equation(int a, int b, int c) {
		_a = a;
		_b = b;
		_c = c;
	}
	void solve();
};

void Equation::solve() {
	if (_a == 0) {
		if (_b == 0)
		{
			if (_c == 0) cout << "5" << endl;
			else cout << "4" << endl;
		}
		else {
			cout << "6" << endl;
			printf("%.2f\n", (float)-_c / _b);
		}
	}
	else {
		int theta;
		theta = _b * _b - 4 * _a*_c;
		if (theta >= 0) {
			if (theta > 0) {
				cout << "1" << endl;
				printf("%.2f %.2f\n", (-_b - sqrt(theta)) / 2.0 / _a ,(-_b + sqrt(theta)) / 2.0 / _a);
			}
			else {
				cout << "2" << endl;
				printf("%.2f\n", -_b / 2.0 / _a);
			}
		}
		else cout << "3" << endl;
	}
	

}
int main() {
	while(1){int a, b, c;
	cin >> a >> b >> c;
	Equation tmp(a, b, c);
	tmp.solve();
	}
	return 0;
}

得分70/100,不知道哪里错了

注意的点:构造函数初始化;保留小数两位输出;换行

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值