题解 | #计算一元二次方程#

计算一元二次方程

https://www.nowcoder.com/practice/7da524bb452441b2af7e64545c38dc26

#include <any>
#include <cmath>
#include <iomanip>
#include <iostream>
using namespace std;

int main() {
    float a, b, c;
    while (cin >> a >> b >> c) { // 注意 while 处理多个 case
        if(a == 0)
        {
            cout<<"Not quadratic equation"<<endl;
        }
        else if (a != 0) {
            float delt = b*b - 4*a*c;
            if(delt == 0)
            {
                float x1,x2;
                x1 = (((-1)*b)+sqrt(delt))/(2*a);
                x2 = abs(x1);
                if(x2 == 0)
                {
                    x1 = 0;
                }
                cout<<fixed<<setprecision(2)<<"x1=x2="<<x1<<endl;
            }
            else if(delt > 0)
            {
                float x1,x2,d;
                x1 = (((-1)*b)-sqrt(delt))/(2*a);
                x2 = (((-1)*b)+sqrt(delt))/(2*a);
                if (x1>x2) {
                    swap(x1, x2);
                }
                d = abs(x1);
                if(d == 0)
                {
                    x1 = 0;
                    x2 = 0;
                }
                cout<<fixed<<setprecision(2)<<"x1="<<x1<<";x2="<<x2<<endl;
            }
            else 
            {
                float d = ((-1)*b)/(2*a),e;
                float x1,x2;
                x1 = (sqrt((-1)*delt))/(2*a);
                x2 = abs(x1);
                e = abs(d);
                if(e == 0)
                {
                    d = 0;
                }
                else {
                    d = d;
                }
                cout<<fixed<<setprecision(2)<<"x1="<<d<<"-"<<x2<<"i;x2="<<d<<"+"<<x2<<"i"<<endl;
            }
        }
    }
}
// 64 位输出请用 printf("%lld")

测试中出现+0与-0,可以用绝对值进行处理。

全部评论

相关推荐

東大沒有派對:这是好事啊(峰哥脸
我的秋招日记
点赞 评论 收藏
分享
09-22 15:45
门头沟学院 Java
谁给娃offer我给...:我也遇到了,我说只要我通过面试我就去,实际上我根本就不会去😁
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务