C语言 求方程 ax^2 + bx + c = 0 的根

求方程ax^2+bx+c=0的根,用3个函数分别求当:b^2-4ac大于0、等于0和小于 0时的根并输出结果。从主函数输入a,b,c的值。

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

// 求当 b^2 - 4ac > 0 时的根
void roots_greater_than_zero(float a, float b, float c) {
    float discriminant = b*b - 4*a*c;
    float root1 = (-b + sqrt(discriminant)) / (2*a);
    float root2 = (-b - sqrt(discriminant)) / (2*a);
    printf("根为:%.2f 和 %.2f\n", root1, root2);
}

// 求当 b^2 - 4ac = 0 时的根
void roots_equal_to_zero(float a, float b, float c) {
    float root = -b / (2*a);
    printf("根为:%.2f\n", root);
}

// 求当 b^2 - 4ac < 0 时的根
void roots_less_than_zero(float a, float b, float c) {
    float discriminant = b*b - 4*a*c;
    float realPart = -b / (2*a);
    float imaginaryPart = sqrt(-discriminant) / (2*a);
    printf("根为:%.2f + %.2fi 和 %.2f - %.2fi\n", realPart, imaginaryPart, realPart, imaginaryPart);
}

int main() {
    float a, b, c;
    printf("输入a, b, c的值:");
    scanf("%f %f %f", &a, &b, &c);
    
    float discriminant = b*b - 4*a*c;
    
    if (discriminant > 0) {
        roots_greater_than_zero(a, b, c);
    } else if (discriminant == 0) {
        roots_equal_to_zero(a, b, c);
    } else {
        roots_less_than_zero(a, b, c);
    }
    
    return 0;
}

解释说明:

b^2-4ac的三种情况:

  • b^2-4ac > 0 时,方程有两个不同的实根,使用公式 (-b±sqrt(b^2-4ac))/(2a) 计算。
  • b^2-4ac == 0 时,方程有一个实根,使用公式 -b/(2a) 计算。
  • b^2-4ac < 0 时,方程有两个共轭复数根。

输入和输出:

  • 主函数从键盘读取系数 a, b, c,并根据判别式的值调用相应函数计算和输出根。

相关推荐

  1. C语言 方程 ax^2 + bx + c = 0

    2024-07-13 18:30:03       19 阅读
  2. 一元二次方程---PTA实验C++

    2024-07-13 18:30:03       37 阅读
  3. 数学小报4 - 三次方程公式 Quadratic Formula

    2024-07-13 18:30:03       24 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-13 18:30:03       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-13 18:30:03       72 阅读
  3. 在Django里面运行非项目文件

    2024-07-13 18:30:03       58 阅读
  4. Python语言-面向对象

    2024-07-13 18:30:03       69 阅读

热门阅读

  1. 第一节 SHELL脚本中的常用命令(6)

    2024-07-13 18:30:03       19 阅读
  2. bert训练的一些技巧(rand() < self.skipgram_prb)

    2024-07-13 18:30:03       18 阅读
  3. Dubbo 负载均衡(Load Balance)

    2024-07-13 18:30:03       19 阅读
  4. 编译的艺术:在Gradle中精调编译器选项

    2024-07-13 18:30:03       22 阅读
  5. 如何防御sql注入攻击

    2024-07-13 18:30:03       20 阅读
  6. html基础篇

    2024-07-13 18:30:03       20 阅读
  7. SpringBoot的启动流程?

    2024-07-13 18:30:03       20 阅读
  8. MyBatisPlus实现增删改查

    2024-07-13 18:30:03       19 阅读
  9. LeetCode 74, 228, 39

    2024-07-13 18:30:03       15 阅读
  10. Oracle字符集修改

    2024-07-13 18:30:03       22 阅读
  11. 力扣 哈希表刷题回顾

    2024-07-13 18:30:03       19 阅读
  12. C++之复合资料型态 第一部(参考 列举 指标)

    2024-07-13 18:30:03       20 阅读