要求:(1)定义一个结构体类型来描述复数。
(2)复数之间的加法、减法、乘法和除法分别用不用的函数来实现。
(3)必须使用结构体指针的方法把函数的计算结果返回。
说明:用户输入:运算符号(+,-,*,/) a b c d.
输出:a+bi,输出时不管a,b是小于0或等于0都按该格式输出,输出时a,b都保留两位。
输入:
- 2.5 3.6 1.5 4.9
输出:
1.00+-1.30i
package 蓝桥;
import java.util.Scanner;
public class Test2 {
public static void main(String[] args){
String str;
char mark;
Scanner input= new Scanner(System.in);
str=input.next();
mark=str.charAt(0);
double[] Num = new double[4];
for(int i=0;i<4;i++){
Num[i]=input.nextDouble();
}
Complex C1 = new Complex(Num[0],Num[1]);
Complex C2 = new Complex(Num[2],Num[3]);
Complex result = new Complex();
switch(mark){
case '+' : result=C1.add(C2); break;
case '-' : result=C1.sub(C2); break;
case '*' : result=C1.mul(C2); break;
case '/' : result=C1.div(C2); break;
}
System.out.printf("%3.2f+%3.2fi", result.Getreal(),result.Getfigure());
}
}
class Complex{
private double real;
private double figure;
public Complex(){}
public Complex(double real,double figure){
this.real=real;
this.figure=figure;
}
public double Getreal(){
return this.real;
}
public double Getfigure(){
return this.figure;
}
public Complex add(Complex otherComplex){
this.real+=otherComplex.real;
this.figure+=otherComplex.figure;
Complex com = new Complex(this.real,this.figure);
return com;
}
public Complex sub(Complex otherComplex){
this.real-=otherComplex.real;
this.figure-=otherComplex.figure;
Complex com = new Complex(this.real,this.figure);
return com;
}
public Complex mul(Complex otherComplex){
double Dreal,Dfigure;
Dreal=this.real*otherComplex.real-this.figure*otherComplex.figure;
Dfigure=this.real*otherComplex.figure+this.figure*otherComplex.real;
Complex com= new Complex(Dreal,Dfigure);
return com;
}
public Complex div(Complex otherComplex){
double Dreal,Dfigure;
Dreal=(this.real*otherComplex.real+this.figure*otherComplex.figure)/
(Math.pow(otherComplex.real, 2)+Math.pow(otherComplex.figure, 2));
Dfigure=(this.figure*otherComplex.real-this.real*otherComplex.figure)/
(Math.pow(otherComplex.real, 2)+Math.pow(otherComplex.figure, 2));
Complex com= new Complex(Dreal,Dfigure);
return com;
}
}