1. 程式人生 > 實用技巧 >Java複數的定義與描述

Java複數的定義與描述

  1 //4.複數的定義與描述
  2 package test;
  3 
  4 import java.util.Scanner;
  5 
  6 public class complex {//複數類
  7       double real;//實部
  8       double image;//虛部
  9       complex(){
 10         Scanner in=new Scanner(System.in);
 11         double real=in.nextDouble();
 12         double image=in.nextDouble();
13 complex(real,image); 14 } 15 public complex(double real, double image) {//有參建構函式 16 this.real = real; 17 this.image = image; 18 } 19 private void complex(double real, double image) {//給無參建構函式呼叫 20 this.real = real; 21 this.image = image; 22 } 23 public
double getReal() { 24 return real; 25 } 26 public void setReal(double real) { 27 this.real = real; 28 } 29 public double getImage() { 30 return image; 31 } 32 public void setImage(double image) { 33 this.image = image; 34 } 35 //複數相加 36 complex add(complex a) {
37 double real2=a.getReal(); 38 double image2=a.getImage(); 39 double newreal=real+real2; 40 double newimage=image+image2; 41 complex result=new complex(newreal, newimage); 42 return result; 43 } 44 //複數相減 45 complex sub(complex a) { 46 double real2=a.getReal(); 47 double image2=a.getImage(); 48 double newreal=real-real2; 49 double newimage=image-image2; 50 complex result=new complex(newreal, newimage); 51 return result; 52 } 53 //複數相乘 54 complex mul(complex a) { 55 double real2=a.getReal(); 56 double image2=a.getImage(); 57 double newreal=real*real2-image*image2; 58 double newimage=image*real2 + real*image2; 59 complex result=new complex(newreal, newimage); 60 return result; 61 } 62 //複數相除 63 complex div(complex a) { 64 double real2=a.getReal(); 65 double image2=a.getImage(); 66 double newreal=(real*real2+image*image2)/(real2*real2 + image2*image2); 67 double newimage=(image*real2 - real*image2)/(real2*real2 + image2*image2); 68 complex result=new complex(newreal, newimage); 69 return result; 70 } 71 // 輸出 72 public void print(){ 73 if(image > 0){ 74 System.out.println(real + " + " + image + "i"); 75 }else if(image < 0){ 76 System.out.println(real + "" + image + "i"); 77 }else{ 78 System.out.println(real); 79 } 80 } 81 } 82 83 84 package test; 85 86 public class complextest { 87 88 public static void main(String[] args) { 89 System.out.println("請輸入第一個複數的實部和虛部:"); 90 complex a1=new complex(); 91 92 System.out.println("請輸入第二個複數的實部和虛部:"); 93 complex a2=new complex(); 94 95 complex add=a1.add(a2); 96 complex sub=a1.sub(a2); 97 complex mul=a1.mul(a2); 98 complex div=a1.div(a2); 99 100 //輸出 101 System.out.println("相加的結果為:"); 102 add.print(); 103 System.out.println("相減結果為:"); 104 sub.print(); 105 System.out.println("相乘的結果為:"); 106 mul.print(); 107 System.out.println("相除的結果為:"); 108 div.print(); 109 } 110 111 }