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".
-
#include <>
-
// This header file is required when using the open root sqrt(d) function
-
#include <>
-
-
int main()
-
{
-
// Finding the roots of a quadratic equation
-
// Code Thoughts:
-
// Three coefficients are entered manually, representing the quadratic coefficient, the primary coefficient, and the constant term;
-
// Determine whether the quadratic coefficients of the input0If it is0The message "The first value entered is not legal, please re-enter it!"
-
// If the coefficient of the quadratic term is not0, using the roots discriminant, calculate whether a quadratic equation has roots;
-
// If the discriminant Δ>= 0 , which represents the equation with two roots, and the output root
-
// If Δ< 0 , suggesting that "the equation has no roots".
-
-
float a , b , c, d, x1, x2;
-
-
printf("Please enter the three coefficients in order: ");
-
scanf("%f %f %f", &a,&b,&c);
-
-
if(a != 0)
-
{
-
d = b * b - 4 * a * c; // discriminant of a root
-
if(d >= 0)
-
{
-
x1 = ((-b + sqrt(d)) / (2 * a)); // formula for finding the root of a problem
-
x2 = ((-b - sqrt(d)) / (2 * a));
-
-
printf("x1 = %.2f;x2 = %.2f", x1, x2);
-
}
-
else
-
{
-
printf("Equations have no roots.");
-
}
-
}
-
else
-
{
-
printf("The first value entered is not legal, please re-enter!");
-
}
-
-
-
return 0;
-
}
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