Giải phương trình bận 2 bằng C

C Chương trình tìm gốc rễ của phương trình bậc hai

Trong ví dụ này, bạn sẽ học cách tìm nghiệm nguyên của phương trình bậc hai trong lập trình C.

Để hiểu được ví dụ này, bạn nên có kiến ​​thức về các chủ đề lập trình C sau :

  • C Programming Operators
  • C if…else Statement

Dạng chuẩn của phương trình bậc hai là:

ax2 + bx + c = 0, where
a, b and c are real numbers and
a != 0

Thuật ngữ này được gọi là phân biệt của một phương trình bậc hai. Nó nói lên bản chất của rễ.b2-4ac

  • If the discriminant is greater than 0, the roots are real and different.
  • If the discriminant is equal to 0, the roots are real and equal.
  • If the discriminant is less than 0, the roots are complex and different.

Hình: Rễ của một phương trình bậc hai

Chương trình tìm gốc của phương trình bậc hai

#include <math.h>
#include <stdio.h>
int main() {
    double a, b, c, discriminant, root1, root2, realPart, imagPart;
    printf("Enter coefficients a, b and c: ");
    scanf("%lf %lf %lf", &a, &b, &c);

    discriminant = b * b - 4 * a * c;

    // condition for real and different roots
    if (discriminant > 0) {
        root1 = (-b + sqrt(discriminant)) / (2 * a);
        root2 = (-b - sqrt(discriminant)) / (2 * a);
        printf("root1 = %.2lf and root2 = %.2lf", root1, root2);
    }

    // condition for real and equal roots
    else if (discriminant == 0) {
        root1 = root2 = -b / (2 * a);
        printf("root1 = root2 = %.2lf;", root1);
    }

    // if roots are not real
    else {
        realPart = -b / (2 * a);
        imagPart = sqrt(-discriminant) / (2 * a);
        printf("root1 = %.2lf+%.2lfi and root2 = %.2f-%.2fi", realPart, imagPart, realPart, imagPart);
    }

    return 0;
} 

Đầu ra

Enter coefficients a, b and c: 2.3
4
5.6
root1 = -0.87+1.30i and root2 = -0.87-1.30i

Trong chương trình này, sqrt()hàm thư viện được sử dụng để tìm căn bậc hai của một số. Để tìm hiểu thêm, hãy truy cập: hàm sqrt() .









Gõ tìm kiếm nhanh...