/*
**
ComplexDemo.java
2012-10-28
**
**/
import java.util.Scanner;
class Complex{
double real,image;
Complex(double real , double image){
this.real = real;
this.image = image;
}
Complex add(Complex complex){
return new Complex(this.real + complex.real , this.image + complex.image);
}
Complex minus(Complex complex){
return new Complex(this.real - complex.real , this.image - complex.image);
}
Complex multiply(Complex complex){
return new Complex(this.real * complex.real - this.image * complex.image ,
this.image * complex.real + this.real * complex.image);
}
Complex divide(Complex complex){
double fenmu = Math.pow(complex.real , 2) + Math.pow(complex.image , 2);
Complex complex1 = new Complex(complex.real , -complex.image);
Complex complex2 = this.multiply(complex1);
return new Complex((double)Math.round(complex2.real*100/fenmu)/100 , (double)Math.round(complex2.image*100/fenmu)/100);
}
String show(){
String str = null;
if(this.real == 0 && this.image == 0 )
str = "0";
if(this.real != 0 && this.image != 0 )
if(this.image > 0)
str = "(" + this.real + "+" + this.image + "i)";
else
str = "(" + this.real + this.image + "i)";
if(this.real == 0 && this.image != 0 )
str = "(" + this.image + "i)";
if(this.real != 0 && this.image == 0 )
str = "(" + "this.real" + ")";
return str;
}
}
class ComplexDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double real1 , image1 , real2 , image2;
String Judge;
while(true){
System.out.println("请输入第一个复数的实部和虚部:");
real1 = scanner.nextDouble();
image1 = scanner.nextDouble();
Complex c1 = new Complex(real1 , image1);
System.out.println("输入的第一个复数为:\n" + c1.show());
System.out.println("\n请输入第二个复数的实部和虚部:");
real2 = scanner.nextDouble();
image2 = scanner.nextDouble();
Complex c2 = new Complex(real2 , image2);
System.out.println("输入的第二个复数为:\n" + c2.show());
System.out.println("\n输入的2个复数的和为:");
System.out.println(c1.show() + " + " + c2.show() + " = " + c1.add(c2).show());
System.out.println("\n输入的2个复数的差为:");
System.out.println(c1.show() + " - " + c2.show() + " = " + c1.minus(c2).show());
System.out.println("\n输入的2个复数的积为:");
System.out.println(c1.show() + " * " + c2.show() + " = " + c1.multiply(c2).show());
System.out.println("\n输入的2个复数的商为:");
if(c2.real == 0 && c2.image == 0)
System.out.println(c1.show() + " / " + c2.show() + "没有意义");
else
System.out.println(c1.show() + " / " + c2.show() + " = " + c1.divide(c2).show());
System.out.println("\n继续计算请输入\"YES\"" +
"\n否则请输入\"N0\"");
Judge = scanner.next();
if(Judge.equals("NO")||Judge.equals("no")){
System.out.println("您已退出");
break;
}
else if(Judge.equals("YES")||Judge.equals("yes")){
continue;
}
}
}
}
Java新手 写的不好...
Java 复数类 实现加减乘除
最新推荐文章于 2024-09-22 12:14:24 发布