用Java声明并测试一个复数类,其方法包括toString()及复数的加、减、乘运算。,javatostring
Java–复数类
package com.edu.gpnu.test;
import java.util.Scanner;
public class Test {
private int a;
private int b;
public Test(int a, int b) {
super();
this.a = a;
this.b = b;
}
public Test() {
this.a = 0;
this.b = 0;
}
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public int getB() {
return b;
}
public void setB(int b) {
this.b = b;
}
@Override
public String toString() {
return "[" + a + "+" + b + "i]";
}
//加法 a+bi & c+di --> (a+c) + (b+d)i
public Test add(Test test) {
return new Test(this.a + test.getA(), this.b + test.getB());
}
//减法 a+bi & c+di --> (a-c) + (b-d)i
public Test sub(Test test) {
return new Test(this.a - test.getA(), this.b - test.getB());
}
//乘法 a+bi & c+di --> (ac-bd) + (bc+ad)i
public Test mul(Test test) {
int a = (this.a * test.a) - (this.b * test.b);
int b = (this.a * test.b) + (this.b * test.a);
Test result = new Test(a, b);
return result;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("第一个复数:");
Test t1 = new Test(scanner.nextInt(), scanner.nextInt());
System.out.println("第二个复数:");
Test t2 = new Test(scanner.nextInt(), scanner.nextInt());
System.out.println("(a + b) = " + t1.add(t2).toString());
System.out.println("(a - b) = " + t1.sub(t2).toString());
System.out.println("(a * b) = " + t1.mul(t2).toString());
System.out.println("(a + b) + a = " + t1.add(t2).add(t1).toString());
}
}
相关文章暂无相关文章