ACM-CSUOJ-equation讨论并解一元二次方程

equation
Description
xrdog有一个众所周知的算式 Ax^2+Bx+C=0

现给定A,B和C,求x

众所周知的是,这样子的方程是有可能有:无解(无实数根)、有有限个解、或者解有无穷多个这几种情况的,你设计的程序当然要能判定这些情况啦

Input
一行三个整数(−103≤a≤103),(−103≤b≤103) 和c(−103≤c≤103)

Output
若无解输出There is no real root of the equation

若有无穷多个解输出The equation has infinite real roots

若有有限个解的话在第一行输出解的个数,第二行从小到大 以空格分割 输出这些解。

注意,输出时方程的根保留两位小数!若是方程具有值相同的实根,这两个实根看做一个。

Sample Input
1 2 1
Sample Output
1
-1.00

一道解一元二次方程的题,只是情况多了一些,疯狂wa (改了N遍),先备份一份,再接着继续改。
WA代码:

#include<iostream>  
#include<cmath>
#include<iomanip>
using namespace std;
int main()
{
	int a, b, c;
	cin >> a >> b >> c;
	if (a == 0 && b == 0)   //无解
	{
		if (c == 0)
			cout << "The equation has infinite real roots";
		else
			cout << "There is no real root of the equation";
	}
	else {
		if (a == 0 && b != 0 && c == 0)
		{
			cout << "1" << endl;
			cout << "0.00";
		}
		else if (a == 0 && b != 0 && c != 0)
		{
			cout << "1" << endl;
			cout << fixed << setprecision(2) << c * (-1) / b;
		}
		else
		{
			double d = b * b - 4.0 * a * c,x1,x2;
			//d==0
			if (d==0)
			{
				if (c==0)
				{
					cout<<"1"<<endl<<"0.00"<<endl;
				}
				else {
					cout<<"1"<<endl<<(-1.0)*b/2*a<<endl;
				}
			}
			//有两个解的情况
			else if(d>0){
				if (a>0)
				{
					x1 = ((-1)*b-sqrt(d))/(2.0*a);
					x2 = ((-1)*b+sqrt(d))/(2.0*a);
					cout<<"2"<<endl<<fixed << setprecision(2) <<x1<<" "<<fixed << setprecision(2) <<x2<<endl;
				}else if(a<0){
					x1 = ((-1)*b-sqrt(d))/(2.0*a);
					x2 = ((-1)*b+sqrt(d))/(2.0*a);
					cout<<"2"<<endl<<fixed << setprecision(2) <<x2<<" "<<fixed << setprecision(2) <<x1<<endl;				}
				
			}
			else{
				cout<<"There is no real root of the equation"<<endl;
			}
		}
	}
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值