이차 방정식의 근 구하기

CBeginner
지금 연습하기

소개

이차 방정식은 ax²+bx+c=0 형태의 방정식으로, 여기서 a, b, c는 상수입니다. 이 Lab 에서는 이차 방정식의 근을 찾는 프로그램을 작성하는 방법을 배웁니다.

이차 방정식을 풀기 위해 다음 공식을 사용합니다.

x = (-b ± sqrt(b² - 4ac)) / 2a

참고: 코딩을 연습하고 gcc 를 사용하여 컴파일하고 실행하는 방법을 배우려면 직접 ~/project/main.c 파일을 생성해야 합니다.

cd ~/project
## create main.c
touch main.c
## compile main.c
gcc main.c -o main
## run main
./main

계수 입력 받기

이차 방정식의 계수 a, b, c 와 같은 값을 사용자로부터 입력받습니다. 이러한 계수는 이차 방정식의 근을 계산하는 데 사용됩니다.

float a, b, c, determinant, r1, r2, real, imag;
printf("\nEnter coefficients a, b and c: ");
scanf("%f%f%f", &a, &b, &c);

판별식 계산

그런 다음 다음 공식을 사용하여 이차 방정식의 판별식 값을 계산합니다.

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

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

근의 성질 확인

그런 다음 2 단계에서 계산된 판별식 값을 기준으로 이차 방정식의 근의 성질을 확인합니다. 판별식이 0 보다 크면 근은 실수이고 서로 다릅니다. 판별식이 0 과 같으면 근은 실수이고 같습니다. 판별식이 0 보다 작으면 근은 복소수이고 허수입니다.

if(determinant > 0)    // both roots are real
{
    r1 = (-b + sqrt(determinant))/2*a;  // Brackets are important
    r2 = (-b - sqrt(determinant))/2*a;
    printf("\n\n\nRoots are: %.2f and %.2f ", r1, r2);
}
else if(determinant == 0)   // both roots are real and equal
{
    r1 = r2 = -b/(2*a); // brackets are important
    printf("\n\n\nRoots are: %.2f and %.2f ", r1, r2);
}
/*
    Determinant < 0 - both roots are imaginary of the
    form real + i*imaginary
*/
else
{
    real = -b/(2*a);
    imag = sqrt(-determinant)/(2*a);
    printf("\n\n\nRoots are %.2f + i%.2f and %.2f - i%.2f ", real, imag, real, imag);
}

근 출력

마지막으로, 3 단계에서 계산된 근의 성질을 기반으로 이차 방정식의 근을 출력합니다.

전체 코드 작성

#include<stdio.h>
#include<math.h>  // This is needed to use sqrt() function

int main()
{
    float a, b, c, determinant, r1, r2, real, imag;
    printf("\nEnter coefficients a, b and c: ");
    scanf("%f%f%f", &a, &b, &c);

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

    if(determinant > 0)    // both roots are real
    {
        r1 = (-b + sqrt(determinant))/2*a;  // Brackets are important
        r2 = (-b - sqrt(determinant))/2*a;
        printf("\n\n\nRoots are: %.2f and %.2f ", r1, r2);
    }
    else if(determinant == 0)   // both roots are real and equal
    {
        r1 = r2 = -b/(2*a); // brackets are important
        printf("\n\n\nRoots are: %.2f and %.2f ", r1, r2);
    }
    /*
        Determinant < 0 - both roots are imaginary of the
        form real + i*imaginary
    */
    else
    {
        real = -b/(2*a);
        imag = sqrt(-determinant)/(2*a);
        printf("\n\n\nRoots are %.2f + i%.2f and %.2f - i%.2f ", real, imag, real, imag);
    }
    printf("\n\n\n\n\t\t\tCoding is Fun !\n\n\n");
    return 0;
}

요약

이 Lab 에서는 이차 방정식의 근을 구하는 C 프로그램을 작성하는 방법을 배웠습니다. 사용자가 이차 방정식의 계수를 입력하면, 판별식 (determinant) 의 값에 따라 결정된 근의 성질을 기반으로 근을 계산했습니다. 그런 다음 근의 성질에 따라 이차 방정식의 근을 출력했습니다.