1.4-20:求一元二次方程的根

本文介绍了一个简单的C++程序,用于求解形如ax² + bx + c = 0的二次方程。程序根据判别式的不同值(大于、等于或小于0)分别计算实数根或复数根。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <stdio.h>
#include <math.h> 
using namespace std;
int main()
{
    double a,b,c,x;
    cin>>a>>b>>c;
    if(b*b==4*a*c)
        printf("x1=x2=%.5f",(-b+sqrt(b*b-4*a*c))/(2*a));
    else
    {
        if(b*b>4*a*c)
            printf("x1=%.5f;x2=%.5f",(-b+sqrt(b*b-4*a*c))/(2*a), (-b-sqrt(b*b-4*a*c))/(2*a));
        else
        {
            x=(-b/(2*a));
            if(x==-0.00000)
                x=0;
            printf("x1=%.5f+%.5fi;x2=%.5f-%.5fi",x,(sqrt(4*a*c-b*b)/(2*a)),x,(sqrt(4*a*c-b*b)/(2*a)));
        }
    }
    return 0;
}
题目描述 有形如:ax 3 +bx 2 +cx+d=0 这样的一个一元三次方程。给出该方程中各项的系数(a,b,c,d 均为实数),并约定该方程存在三个不同实的范围在 −100 至 100 之间),且之差的绝对值 ≥1。要由小到大依次在同一行输出这三个实(之间留有空格),并精确到小数点后 2 位。 提示:记方程 f(x)=0,若存在 2 个数 x 1 ​ 和 x 2 ​ ,且 x 1 ​ <x 2 ​ ,f(x 1 ​ )×f(x 2 ​ )<0,则在 (x 1 ​ ,x 2 ​ ) 之间一定有一个。 输入格式 一行,4 个实数 a,b,c,d。 输出格式 一行,3 个实,从小到大输出,并精确到小数点后 2 位。 输入输出样例 输入 #1复制 1 -5 -4 20 输出 #1复制 -2.00 2.00 5.00#include<iostream> #include <cmath> #include<iomanip> #include <algorithm> #include<vector> #include <queue> #include <unordered_map> #include<climits> using namespace std; double f(double a,double b,double c,double d,double x) { return a * x * x * x + b * x * x + c * x + d; } double findroot(double a,double b,double c,double d,double left,double right) { double mid; while (right - left > 1e-8) { mid = (left + right) / 2; if (f(a, b, c, d, mid) * f(a, b, c, d, left) < 0) { right = mid; } else left = mid; } return(left + right) / 2; } int main() { double a, b, c, d; cin >> a >> b >> c >> d;//-100到100之间三个,f=0 double roots[3] = { -101,-101,-101 }; int count = 0; for (double x = -100;x <= 100 && count < 3;x += 1) { double y1 = f(a, b, c, d, x); double y2 = f(a, b, c, d, x + 1); if (fabs(f(a, b, c, d, x)) < 1e-8) { roots[count++] = x; continue; } if (y1 * y2 <0&&count<3) { roots[count++] = findroot(a, b, c, d, x, x + 1); } } cout << fixed << setprecision(2) << roots[0] << " " << roots[1] << " " << roots[2] << endl; return 0; }为什么输入1 -4.65 2.25 1.4得到的是-0.35 1.00 1.00而不是正确答案-0.35 1.00 4.00呢
最新发布
03-12
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值