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

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

ในบทความนี้ เราจะเรียนรู้วิธาบวกจำนวนเชิงซ้อน (Complex Numbers) ในภาษา Java จำนวนเชิงซ้อนประกอบด้วยส่วนจริง (Real) และส่วนจินตภาพ (Imaginary)

ตัวอย่างการทำงาน

อินพุต:

15 + i24 และ 3 + i7

เอาต์พุต:

18 + i31

อัลกอริทึม

  1. เริ่มต้นโปรแกรม
  2. สร้างคลาส ComplexNumbers มีฟิลด์ real และ imaginary
  3. สร้างเมธอด AddComplexNumbers บวกส่วนจริงกับจริง จินตภาพกับจินตภาพ
  4. สร้างวัตถุ 2 ตัว เรียกเมธอดบวก แสดงผล
  5. จบโปรแกรม

ตัวอย่างที่ 1: ใช้คลาสแยกเมธอดบวก

import java.util.*;

class ComplexNumbers {
    int real, imaginary;

    ComplexNumbers() {}
    ComplexNumbers(int real, int imaginary) {
        this.real = real;
        this.imaginary = imaginary;
    }

    ComplexNumbers add(ComplexNumbers other) {
        ComplexNumbers result = new ComplexNumbers();
        result.real = this.real + other.real;
        result.imaginary = this.imaginary + other.imaginary;
        return result;
    }
}

public class MainFunction {
    public static void main(String[] args) {
        System.out.println("Required packages have been imported");

        ComplexNumbers c1 = new ComplexNumbers(15, 24);
        System.out.println("First complex number: " + c1.real + " + i" + c1.imaginary);

        ComplexNumbers c2 = new ComplexNumbers(3, 7);
        System.out.println("Second complex number: " + c2.real + " + i" + c2.imaginary);

        ComplexNumbers result = c1.add(c2);
        System.out.println("Sum: " + result.real + " + i" + result.imaginary);
    }
}

ตัวอย่างที่ 2: ใช้ static method

public class ComplexNumber {
    int real, imaginary;

    public ComplexNumber(int r, int i) {
        this.real = r;
        this.imaginary = i;
    }

    public void print() {
        System.out.print(this.real + " + i" + this.imaginary);
    }

    public static ComplexNumber add(ComplexNumber n1, ComplexNumber n2) {
        ComplexNumber result = new ComplexNumber(0, 0);
        result.real = n1.real + n2.real;
        result.imaginary = n1.imaginary + n2.imaginary;
        return result;
    }

    public static void main(String arg[]) {
        ComplexNumber c1 = new ComplexNumber(15, 24);
        ComplexNumber c2 = new ComplexNumber(3, 7);

        System.out.println("The two complex numbers are:");
        c1.print();
        System.out.print(" and ");
        c2.print();

        ComplexNumber result = add(c1, c2);
        System.out.println("\nThe sum is:");
        result.print();
    }
}

หมายเหตุ

Java ไม่มีชนิดข้อมูล Complex Number ในตัว ต้องสร้างคลาสเอง หรือใช้ไลบรารีเช่น Apache Commons Math (Complex class)