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

บวกจำนวนเชิงซ้อน (Complex Numbers) ด้วย Struct และ Function ใน C


บวกจำนวนเชิงซ้อน 2 จำนวน โดยใช้ Struct เก็บส่วนจริง (real) และจินตภาพ (imaginary) แล้วส่งเข้า Function

อัลกอริทึม

  1. ประกาศ struct complex มี real, imag
  2. รับค่าจำนวนเชิงซ้อนตัวที่ 1 และ 2
  3. เรียกฟังก์ชัน addition() คืนค่า struct ผลลัพธ์
  4. ในฟังก์ชัน: real = r1+r2, imag = i1+i2

โปรแกรมตัวอย่าง

#include <stdio.h>

typedef struct complex {
    float real;
    float imag;
} complex;

complex addition(complex n1, complex n2);

int main() {
    complex num1, num2, result;
    
    printf("Enter real and imag of 1st complex: ");
    scanf("%f %f", &num1.real, &num1.imag);
    
    printf("Enter real and imag of 2nd complex: ");
    scanf("%f %f", &num2.real, &num2.imag);
    
    result = addition(num1, num2);
    printf("Result = %.1f + %.1fi\n", result.real, result.imag);
    return 0;
}

complex addition(complex n1, complex n2) {
    complex temp;
    temp.real = n1.real + n2.real;
    temp.imag = n1.imag + n2.imag;
    return temp;
}

ผลลัพธ์

entering real and imag parts of first complex no: 3 4
entering real and imag parts of second complex no: 2 5
result = 5.0 + 9.0i