解题思路:
题目要求使用重载运算,个人觉得应该是没必要,直接用if-else判断运算符就行了;
这个题目其实本质就是引用类型作形参的考察,也就是注意作形参时的地址传递;
注意事项:
注意输出虚数的格式,例如,虚数a+bi中,a=0,b!=0时,应该输出bi,不一一举例了,会在代码中体现。
参考代码:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); Complex c = new Complex(); int a = sc.nextInt(); int b = sc.nextInt(); Complex c1 = new Complex(a, b); char s = sc.next().charAt(0); int e = sc.nextInt(); int f = sc.nextInt(); Complex c2 = new Complex(e, f); if (s == '+') { c.add(c1, c2); c.print(); } if (s == '-') { c.min(c1, c2); c.print(); } } } class Complex { int a; int b; int c; int d; public Complex() {//空的构造方法 } public Complex(int a, int b) {//带参数的构造方法 this.a = a; this.b = b; } public void add(Complex c1, Complex c2) {//实现加法,形参为Complex引用类型 this.c = c1.a + c2.a; this.d = c1.b + c2.b; } public void min(Complex c1, Complex c2) {//实现减法,形参为Complex引用类型 this.c = c1.a - c2.a; this.d = c1.b - c2.b; } public void print() { if ((c > 0 && d > 0) || (c < 0 && d > 0)) { System.out.println(c + "+" + d + "i"); } if ((c > 0 && d < 0) || (c < 0 && d < 0)) { System.out.println(c +""+d + "i"); } if (c == 0 && d != 0) { System.out.println(d + "i"); } if (c == 0 && d == 0) { System.out.println(c); } if (c != 0 && d == 0) { System.out.println(c); } } }
0.0分
2 人评分