猿问

如下所示,请问再添加一个 add() 方法使之能进行两个复数之间的加法吗?

public class Overload {
int m,n;
Overload( ) {
m = 0;
n = 0;
}
Overload(int a, int b) {
m = a;
n = b;
}
int add( ) {
System.out.println("无参加法 "+m+"+"+n+"="+(m+n));
return m+n;
}
int add(int a, int b) {
System.out.println("整型加法 "+a+"+"+b+"="+(a+b));
return a+b;
}
double add(double a, double b) {
System.out.println("实型加法 "+a+"+"+b+"="+(a+b));
return a+b;
}
double add(int a, int b, double c) {
System.out.println("混合加法 "+a+"+"+b+"+"+c+"="+(a+b+c));
return a+b+c;
}

public static void main(String[] args) {
int ix,iy;
double dx,dy;
Overload ov = new Overload();
ix = ov.add();
iy = ov.add(3,6);
dx =ov.add(2.1, 5.3);
dy = ov.add(3, 6, 2.2);
}

}
再添加一个 add() 方法使之能进行两个复数之间的加法。

茅侃侃
浏览 203回答 3
3回答

温温酱

复数的定义类型在java中是”Complex “。之后通过实参和虚残分别进行相加即可。代码如下:public Complex add(Complex realOne,Complex realTwo){return realOne.add(realTwo);}class Complex{int real;int imaginary;Complex(int real,int imaginary){this.real = real;this.imaginary = imaginary;}public Complex add(Complex realTwo){return new Complex( this.real+realTwo.real,this.imaginary+realTwo.imaginary);}public String toString(){return real + "+" + imaginary + "i";}}备注:toString方法是某些方法中要求重新的方法,其值就是最终的结果。重载就是方法名相同,其余的可以任意的变换(参数类型,个数)。

呼唤远方

参数的个数不一样举例一:void fun(int x) ;void fun(double x) ;这个叫参数类型不同的方法重载 。举例二:void fun(int x) ;void fun(int x, int y) ;这个叫参数个数不同的方法重载 。返回值不同不能代表方法是否重载,方法名不一样也不叫方法重载,只能算是多个方法!

哆啦的时光机

public Complex add(Complex a,Complex b){return a.add(b);}class Complex{int real;int imaginary;Complex(int real,int imaginary){this.real = real;this.imaginary = imaginary;}public Complex add(Complex b){return new Complex( this.real+b.real,this.imaginary+b.imaginary);}public String toString(){return real + "+" + imaginary + "i";}}
随时随地看视频慕课网APP
我要回答