复数的运算(类和对象)
Time Limit: 1000MS
Memory Limit: 65536KB
Problem Description
设计一个类Complex,用于封装对复数的下列操作:
成员变量:实部real,虚部image,均为整数变量;
构造方法:无参构造方法、有参构造方法(参数2个)
成员方法:含两个复数的加、减、乘操作。
复数相加举例: (1+2i)+(3+4i)= 4 + 6i
复数相减举例: (1+2i)-(3+4i)= -2 - 2i
复数相乘举例: (1+2i)*(3+4i)= -5 + 10i
要求:对复数进行连环运算。
Input
输入有多行。
第一行有两个整数,代表复数X的实部和虚部。
后续各行的第一个和第二个数表示复数Y的实部和虚部,第三个数表示操作符op: 1——复数X和Y相加;2——复数X和Y相减;3——复数X和Y相乘。
Output
计算数据输出其简化复数形式,如:-2-2i、-4、-3i、1+2i、0。
Example Input
1 1 3 4 2 5 2 1 2 -1 3 0 2 2
Example Output
5-7i
import java.text.DecimalFormat;
import java.util.Scanner;
class Complex { // 复数类
double real; // 实部
double image; // 虚部
Complex() {
Scanner input = new Scanner(System.in);
double real = input.nextDouble();
double image = input.nextDouble();
Complex(real, image);
}
private void Complex(double real, double image) {
this.real = real;
this.image = image;
}
Complex(double real, double image) {
this.real = real;
this.image = image;
}
public double getReal() {
return real;
}
public void setReal(double real) {
this.real = real;
}
public double getImage() {
return image;
}
public void setImage(double image) {
this.image = image;
}
Complex add(Complex a) {
double real2 = a.getReal();
double image2 = a.getImage();
double newReal = real + real2;
double newImage = image + image2;
Complex result = new Complex(newReal, newImage);
return result;
}
Complex sub(Complex a) {
double real2 = a.getReal();
double image2 = a.getImage();
double newReal = real - real2;
double newImage = image - image2;
Complex result = new Complex(newReal, newImage);
return result;
}
Complex mul(Complex a) {
double real2 = a.getReal();
double image2 = a.getImage();
double newReal = real * real2 - image * image2;
double newImage = image * real2 + real * image2;
Complex result = new Complex(newReal, newImage);
return result;
}
public void print() {
DecimalFormat zero = new DecimalFormat("#0");
if (image > 0) {
System.out.println(zero.format(real) + "+" + zero.format(image) + "i");
} else if (image < 0) {
System.out.println(zero.format(real) + "" + zero.format(image) + "i");
} else {
System.out.println(zero.format(real));
}
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int x1 = sc.nextInt();
int y1 = sc.nextInt();
Complex data1 = new Complex(x1,y1);
while(sc.hasNext()) {
int x = sc.nextInt();
int y = sc.nextInt();
Complex data2 = new Complex(x,y);
int o = sc.nextInt();
if(o == 1) {
data1 = data1.add(data2);}
else if(o == 2) {
data1 = data1.sub(data2);
}
else if(o == 3) {
data1 = data1.mul(data2);
}
}
data1.print();
}
}