代数中的一元二次方程可以定义为任何可以写成 ax^2+bx+c=0 形式的方程。 为了更好地理解这个查找一元二次方程根的 C 语言程序示例,我们始终建议您学习下面列出的 C 语言编程的基础知识。
在代数中,一元二次方程是可以重新排列成 'ax^2+bx+c=0' 形式的方程,其中 'x' 代表一个未知量,而 'a'、'b' 和 'c' 是不等于 0 的数字。如果 'a = 0',那么它不是一元二次方程,它被称为线性方程。数字 'a'、'b' 和 'c' 是方程的系数,而 'x' 是方程中需要找出未知值。在这个 C 语言程序中,我们需要解一元二次方程并找出它的根。
C 语言程序查找非零系数一元二次方程的所有根是一个有点长的程序,但是如果你知道程序背后的逻辑,它会非常简单。我们使用公式 "disc = b*b - 4.0*a*c",在找到 "disc" 后,我们可以根据 disc 的值大于或小于零来检查根是实数还是虚数。
注意:检查一元二次方程,如果 'a=0' 则它不是一元二次方程。现在检查 'A' 或 'B' 或 'C' 是否为零。如果是,我们无法确定根。否则应用公式 "b*b - 4*a*c"。最后,检查结果是大于零、小于零还是等于零。
步骤 1:将所需的头文件库导入 C 语言程序,以使用所需的内置函数。
步骤 2:使用 printf 和 scanf 内置函数接受 A、B 和 C 的值。
步骤 3:检查 A 的值是否不等于零。如果是,则它不是一元二次方程。
步骤 4:使用 'else' 语句,通过公式 'B*B - 4.0*A*C' 检查 'disc' 的值。
步骤 5:如果 disc 小于零,则为虚根。
步骤 6:使用公式找出实根和虚根,并使用 printf 打印根。
步骤 7:使用 'else if' 语句检查 disc 是否等于零,此时根将相等且为实数。
步骤 8:使用公式计算根,并使用打印语句打印根。
步骤 9:使用 'else if' 语句检查 disc 是否大于零。如果是,则打印根为实数且不相等。
步骤 10:使用特定公式计算两个根,并使用 C 语言编程中的 printf 内置函数打印结果。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void main() {
float A, B, C, root1, root2;
float realp, imagp, disc;
printf("Enter the values of A, B and C\n");
scanf("%f %f %f", & A, & B, & C); /* If A = 0, it is not a quadratic equation */
if (A == 0 || B == 0 || C == 0) {
printf("Error: Roots cannot be determined\n");
exit(1);
} else {
disc = B * B - 4.0 * A * C;
if (disc < 0) {
printf("Imaginary Roots\n");
realp = -B / (2.0 * A);
imagp = sqrt(abs(disc)) / (2.0 * A);
printf("Root1 = %f +i %f\n", realp, imagp);
printf("Root2 = %f -i %f\n", realp, imagp);
} else if (disc == 0) {
printf("Roots are real and equal\n");
root1 = -B / (2.0 * A);
root2 = root1;
printf("Root1 = %f \n", root1);
printf("Root2 = %f \n", root2);
} else if (disc > 0) {
printf("Roots are real and distinct\n");
root1 = (-B + sqrt(disc)) / (2.0 * A);
root2 = (-B - sqrt(disc)) / (2.0 * A);
printf("Root1 = %f \n", root1);
printf("Root2 = %f \n", root2);
}
}
}
RUN 1 Enter the values of A, B and C 3 2 1 Imaginary Roots Root1 = -0.333333 +i 0.471405 Root2 = -0.333333 -i 0.471405 RUN 2 Enter the values of A, B and C 1 2 1 Roots are real and equal Root1 = -1.000000 Root2 = -1.000000 RUN 3 Enter the values of A, B and C 3 5 2 Roots are real and distinct Root1 = -0.666667 Root2 = -1.000000