Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

เขียนโปรแกรม C หารากสมการกำลังสอง (Quadratic Equation)

ปัญหา

หาค่าราก (Roots) ของสมการกำลังสอง: ax² + bx + c = 0

วิเคราะห์

  • Input: a, b, c (a ≠ 0)
  • Output: r1, r2 (รากสองค่า)
  • Discriminant (d): d = b² - 4ac

กรณีของราก

Discriminantลักษณะรากสูตร
d > 0รากจริง สองค่า ต่างกันr = (-b ± √d) / 2a
d = 0รากจริง ค่าเดียว (Double Root)r = -b / 2a
d < 0รากจินตภาพ (Complex)r = (-b ± i√|d|) / 2a

อัลกอริทึม

  1. Start
  2. Read a, b, c
  3. Compute d = b² - 4ac
  4. If d > 0 → Compute r1, r2 (Real & Distinct)
  5. Else if d == 0 → Compute r1 = r2 (Real & Equal)
  6. Else → Print "Imaginary Roots"
  7. Stop

โค้ด C (Basic)

#include <stdio.h>
#include <math.h>

int main() {
    float a, b, c, r1, r2, d;
    
    printf("Enter a b c: ");
    scanf("%f %f %f", &a, &b, &c);
    
    if(a == 0) {
        printf("Not a quadratic equation (a=0)\n");
        return 1;
    }
    
    d = b*b - 4*a*c;
    
    if(d > 0) {
        r1 = (-b + sqrt(d)) / (2*a);
        r2 = (-b - sqrt(d)) / (2*a);
        printf("Real and Distinct Roots:\n");
        printf("r1 = %.4f\n", r1);
        printf("r2 = %.4f\n", r2);
    } else if(d == 0) {
        r1 = r2 = -b / (2*a);
        printf("Real and Equal Roots:\n");
        printf("r1 = r2 = %.4f\n", r1);
    } else {
        float real = -b / (2*a);
        float imag = sqrt(-d) / (2*a);
        printf("Complex Roots:\n");
        printf("r1 = %.4f + %.4fi\n", real, imag);
        printf("r2 = %.4f - %.4fi\n", real, imag);
    }
    
    return 0;
}

ผลลัพธ์ทดสอบ

Case 1: a=1, b=4, c=3   (d=4>0)
Real and Distinct Roots:
r1 = -1.0000
r2 = -3.0000

Case 2: a=1, b=2, c=1   (d=0)
Real and Equal Roots:
r1 = r2 = -1.0000

Case 3: a=1, b=1, c=4   (d=-15<0)
Complex Roots:
r1 = -0.5000 + 1.9365i
r2 = -0.5000 - 1.9365i

ข้อควรระวัง

  • Compile ต้อง Link Math Library: gcc quad.c -o quad -lm
  • ตรวจสอบ a ≠ 0 (ไม่ใช่สมการกำลังสอง)
  • ใช้ double แทน float เพื่อ Precision ดีกว่า
  • Handling ของ Floating Point Comparison (d == 0 อาจผิดจาก Precision) → ใช้ Epsilon

เวอร์ชันปรับปรุง (Robust)

#include <stdio.h>
#include <math.h>

#define EPSILON 1e-9

int main() {
    double a, b, c, d, r1, r2;
    
    printf("Enter coefficients a, b, c: ");
    if(scanf("%lf %lf %lf", &a, &b, &c) != 3) {
        printf("Invalid input\n");
        return 1;
    }
    
    if(fabs(a) < EPSILON) {
        printf("Not a quadratic equation (a ≈ 0)\n");
        return 1;
    }
    
    d = b*b - 4*a*c;
    
    if(d > EPSILON) {
        r1 = (-b + sqrt(d)) / (2*a);
        r2 = (-b - sqrt(d)) / (2*a);
        printf("Two distinct real roots: %.6f, %.6f\n", r1, r2);
    } else if(fabs(d) <= EPSILON) {
        r1 = -b / (2*a);
        printf("One real root (double): %.6f\n", r1);
    } else {
        double real = -b / (2*a);
        double imag = sqrt(-d) / (2*a);
        printf("Complex roots: %.6f ± %.6fi\n", real, imag);
    }
    return 0;
}