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

เขียนโปรแกรม C บวกจำนวนเชิงซ้อน (Complex Numbers)

โจทย์

บวกจำนวนเชิงซ้อน 2 จำนวน ที่ผู้ใช้ป้อนขณะรันโปรแกรม

วิธีแก้ปัญหา

จำนวนเชิงซ้อนประกอบด้วยส่วนจริง (real) และส่วนจินตภาพ (imaginary) เขียนในรูป a + ib

ตัวอย่าง: (4+2i) + (5+3i) = 9+5i

โปรแกรม

#include <stdio.h>
struct complexNumber {
    int realnumber, imaginarynumber;
};
int main() {
    struct complexNumber x, y, z;
    printf("enter first complex number (real imag): ");
    scanf("%d %d", &x.realnumber, &x.imaginarynumber);
    printf("enter second complex number (real imag): ");
    scanf("%d %d", &y.realnumber, &y.imaginarynumber);
    z.realnumber = x.realnumber + y.realnumber;
    z.imaginarynumber = x.imaginarynumber + y.imaginarynumber;
    printf("Sum of the complex numbers: (%d) + (%di)\n", z.realnumber, z.imaginarynumber);
    return 0;
}

ผลลัพธ์

Enter first complex number (real imag): 2 3
Enter second complex number (real imag): 4 5
Sum of the complex numbers: (6) + (8i)