VB.NET IIF函式, 慎用,有坑!C# 三目運算子 a?b:c
阿新 • • 發佈:2021-01-14
Java 實驗二 面向物件程式設計
定義一個運算介面Calculate,它定義了四種方法:加(add)、減(sub)、乘(mul)、除(div)。
定義一個複數類Complex,它具有實部和虛部、構造方法、set方法(重新設定複數的值),以及public String ToString()方法
(實現複數的格式化輸出:如 r3=3+4i 題目要求必須按照該種格式輸出)。定義一個高階複數類advComplex,它繼承複數類Complex,實現運算介面Calculate定義的加、減、乘、除四種方法。
interface Calculate{ //定義一個運算介面
Complex add( Complex r);
Complex sub(Complex r);
Complex mul(Complex r);
Complex div(Complex r); //定義四種方法:加減乘除
}
class Complex{ //定義一個複數類Complex,具有實部和虛部
double x,y;
public Complex(double r,double i){ //構造方法
x=r;y=i;
}
public void set(double r,double i){ //設定方法(重新設定複數的值)
x=r;y=i;
}
public String toString(){ //物件描述資訊(實現複數的格式化輸出:如r3= 3+4i)
if(y>0)
if(x==0)
return y+"i";
else
return x+"+"+y+"i";
else if(y==0)
return x+"";
else
if(x==0)
return y+"i";
return x+""+y+"i";
}
}
public class advComplex extends Complex //定義一個高階複數類advComplex,它繼承複數類Complex
implements Calculate{ //實現Calculate介面(implements關鍵詞)
public advComplex(double r,double i){
super(r,i); //呼叫父類構造方法
}
public Complex add(Complex r2){ //將複數與r2相加
return new Complex(x+r2.x,y+r2.y);
}
public Complex sub(Complex r2){ //將複數與r2相減
return new Complex(x-r2.x,y-r2.y);
}
public Complex mul(Complex r2){
double a=x*r2.x-y*r2.y;
double b=y*r2.x+x*r2.y;
return new Complex(a,b);
}
public Complex div(Complex r2){
if(r2.x==0&&r2.y==0){
System.out.println("Number Divided is 0,Error!");
System.exit(0);
}
double c=r2.x*r2.x+r2.y*r2.y;
double a=(x*r2.x+y*r2.y)/c;
double b=y*r2.x-x*r2.y;
return new Complex(a,b);
}
public static void main(String args[]){
advComplex r1=new advComplex(6,6);
advComplex r2=new advComplex(-6,8);
System.out.println("r1="+r1+",r2="+r2);
Complex r3=r1.add(r2); //r1+r2=r3
System.out.println("r1+r2="+r3);
r3=r1.sub(r2); //r1-r2=r3
System.out.println("r1-r2="+r3);
r1.set(1,2);
r2.set(1,-2);
System.out.println("r1="+r1+",r2="+r2);
Complex r4=r1.mul(r2); //r4=r1*r2
System.out.println("r1*r2="+r4);
r4=r1.div(r2); //r4=r1/r2
System.out.println("r1/r2="+r4);
}
}