1048 Problem E 求方程的根

题目描述

求方程的根,用三个函数分别求当 b2−4ac 大于 0、等于 0 和小于 0 时的根,并输出结果。从主函数输入 a、b、c 的值。

输入输出样例

样例输入 #1
4 1 1
样例输出 #1
x1=-0.125+0.484i x2=-0.125-0.484i

提示

主函数已给定如下,提交时不需要包含下述主函数

C:

int main()
{
    float a, b, c, q;
    void shigen(float, float, float);
    void denggen(float, float);
    void xugen(float, float, float);
    scanf("%f%f%f", &a, &b, &c);
    q= b*b - 4*a*c;
    if (q > 0) shigen(a, b, q);
    else if (q == 0) denggen(a, b);
    else xugen(a, b, q);
    return 0;
}

代码:

#include <stdio.h>
#include <math.h>
#include <complex.h>

// 当 D > 0 时,求两个不同的实数根
void shigen(float a, float b, float q) {
    float sqrt_q = sqrt(q);
    float x1 = (-b + sqrt_q) / (2 * a);
    float x2 = (-b - sqrt_q) / (2 * a);
    printf("x1=%.3f x2=%.3f\n", x1, x2);
}

// 当 D = 0 时,求一个重根
void denggen(float a, float b) {
    float x = -b / (2 * a);
    printf("x1=x2=%.3f\n", x);
}

// 当 D < 0 时,求两个复数根
void xugen(float a, float b, float q) {
    float real_part = -b / (2 * a);
    float imaginary_part = sqrt(-q) / (2 * a);
    printf("x1=%.3f+%.3fi x2=%.3f-%.3fi\n", real_part, imaginary_part, real_part, imaginary_part);
}

int main() {
    float a, b, c, q;
    void shigen(float, float, float);
    void denggen(float, float);
    void xugen(float, float, float);

    // 输入系数 a, b, c
    scanf("%f%f%f", &a, &b, &c);
    q = b * b - 4 * a * c; // 计算判别式

    // 根据判别式的值调用不同的函数
    if (q > 0) {
        shigen(a, b, q);
    } else if (q == 0) {
        denggen(a, b);
    } else {
        xugen(a, b, q);
    }
    
    return 0;
}

 编译结果:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值