web123456

C language - quadratic equations (root formula)

逻辑概念:

        The format of a quadratic equation is:ax²+bx+c=0(a≠0)

The formula for finding the root is Δ = b²-4×a×c

         

This program needs to use the header file #include <> among the sqrt()function (math.)

        The sqrt() function is used to compute a non-negative real numberThe square root of (i.e., the open root sign).

Code Example:

  1. #include <>
  2. #include <>
  3. int main()
  4. {
  5. float a,b,c,q;
  6. float x1,x2;
  7. printf("Please enter the a:");
  8. scanf("%f",&a);
  9. printf("Please enter the b:");
  10. scanf("%f",&b);
  11. printf("Please enter the c:");
  12. scanf("%f",&c);
  13. q = b*b - 4*a*c;
  14. x1 = (-b+sqrt(q)) / (2*a);
  15. x2 = (-b-sqrt(q)) / (2*a);
  16. printf("\n equation is %.1fx² + %.1fx + %.1f = 0\n",a,b,c);
  17. if(q < 0)
  18. printf("∵ Δ < 0\n∴ The equation has no solution\n");
  19. else if(q == 0)
  20. printf("∵ Δ = 0\n∴ x1=x2=%.2f",x1);
  21. else
  22. printf("∵ Δ = %.2f\nOpening the root sign gives %.2f\n∴ x1=%.2f\nx2=%.2f\n",q,sqrt(q),x1,x2);
  23. return 0;
  24. }

Input Example:

  1. Please enter the a:5
  2. Please enter the b:7
  3. Please enter the c:2

Example output:

  1. Please enter the a:5
  2. Please enter the b:7
  3. Please enter the c:2
  4. The equation is5.0x²+7.0x+2.0=0
  5. ∵ Δ = 9.00
  6. lit. opening the root sign gets3.00
  7. ∴ x1=-0.40
  8. x2=-1.00