[C.C++] C语言 计算一元二次方程 ax²+bx+c=0

879 0
Honkers 2025-3-17 00:36:16 | 显示全部楼层 |阅读模式

方法一:常规计算

  1. #include<stdio.h>
  2. #include<math.h>
  3. void main(){
  4. float a,b,c,d,x1,x2;
  5. printf("请输入a的值:");
  6. scanf("%f",&a);
  7. printf("请输入b的值:");
  8. scanf("%f",&b);
  9. printf("请输入c的值:");
  10. scanf("%f",&c);
  11. d=b*b-4*a*c;
  12. if(d>0){
  13. x1=(-b+sqrt(d))/(2*a);
  14. x2=(-b-sqrt(d))/(2*a);
  15. printf("x1=%g,x2=%g",x1,x2);
  16. }else if(d==0){
  17. x1=x2=-b/(2*a);
  18. printf("x1=x2=%g",x1);
  19. }else{
  20. printf("无解");
  21. }
  22. }
复制代码

方法二:函数调用,包含共轭复根

  1. #include<stdio.h>
  2. #include<math.h>
  3. float x1,x2,disc,p,q;
  4. void greater_than_zero(float a,float b){
  5. x1=(-b+sqrt(disc))/(2*a);
  6. x2=(-b-sqrt(disc))/(2*a);
  7. }
  8. void equal_to_zero(float a,float b){
  9. x1=x2=(-b)/(2*a);
  10. }
  11. void smaller_than_zero(float a,float b){
  12. p=-b/(2*a);
  13. q=sqrt(-disc)/(2*a);
  14. }
  15. int main(){
  16. float a,b,c;
  17. printf("input a,b,c:");
  18. scanf("%f,%f,%f",&a,&b,&c);
  19. printf("equation:%g*x*x+%g*x+%g=0\n",a,b,c);
  20. disc=b*b-4*a*c;
  21. printf("root:\n");
  22. if(disc>0){
  23. greater_than_zero(a,b);
  24. printf("x1=%f\tx2=%f\n",x1,x2);
  25. }else if(disc==0){
  26. equal_to_zero(a,b);
  27. printf("x1=%f\tx2=%f\n",x1,x2);
  28. }else{
  29. smaller_than_zero(a,b);
  30. printf("x1=%f+%f\tx2=%f-%f\n",p,q,p,q);
  31. }
  32. return 0;
  33. }
复制代码

① 两个不等的实根


② 两个相等的实根

③ 两个共轭复根

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Honkers

荣誉红客

关注
  • 4010
    主题
  • 36
    粉丝
  • 0
    关注
这家伙很懒,什么都没留下!

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2025 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行