web123456

Finding the roots of a quadratic equation using the c language

To write this example in c, you need to know the mathematical formulas.

quadratic equation in one variableThe expression is: a * x * x + bx + c = 0 (where a ≠ 0)

The discriminant of the root is: Δ = b * b - 4 * a * c;

The rooting formula is:

code idea

Three coefficients are entered manually, representing the quadratic coefficient, the primary coefficient, and the constant term;

判断输入的二次项系数是否为0,如果为0,draw attention to sth.“The first value entered is not legal,Please re-enter!”;

If the coefficient of the quadratic term is not zero, use the root's discriminant to calculate whether the quadratic equation has roots;

If the discriminant Δ >= 0 ,means that the equation has two roots, output the roots;

If Δ < 0 , prompt "Equation has no roots".

  1. #include <>
  2. // This header file is required when using the open root sqrt(d) function
  3. #include <>
  4. int main()
  5. {
  6. // Finding the roots of a quadratic equation
  7. // Code Thoughts:
  8. // Three coefficients are entered manually, representing the quadratic coefficient, the primary coefficient, and the constant term;
  9. // Determine whether the quadratic coefficients of the input0If it is0The message "The first value entered is not legal, please re-enter it!"
  10. // If the coefficient of the quadratic term is not0, using the roots discriminant, calculate whether a quadratic equation has roots;
  11. // If the discriminant Δ>= 0 , which represents the equation with two roots, and the output root
  12. // If Δ< 0 , suggesting that "the equation has no roots".
  13. float a , b , c, d, x1, x2;
  14. printf("Please enter the three coefficients in order: ");
  15. scanf("%f %f %f", &a,&b,&c);
  16. if(a != 0)
  17. {
  18. d = b * b - 4 * a * c; // discriminant of a root
  19. if(d >= 0)
  20. {
  21. x1 = ((-b + sqrt(d)) / (2 * a)); // formula for finding the root of a problem
  22. x2 = ((-b - sqrt(d)) / (2 * a));
  23. printf("x1 = %.2f;x2 = %.2f", x1, x2);
  24. }
  25. else
  26. {
  27. printf("Equations have no roots.");
  28. }
  29. }
  30. else
  31. {
  32. printf("The first value entered is not legal, please re-enter!");
  33. }
  34. return 0;
  35. }
for example1:ratio a = 0, b = 2, c = 1 hour,The results of the run are as follows

for example2:ratio a = 1, b = 2, c = 1 hour,The results of the run are as follows

for example3:ratio a = 1, b = 3, c = 2 hour,The results of the run are as follows

for example4:ratio a = 1, b = 0, c = 1 hour,The results of the run are as follows