使用OOP结构增加和减少复数 [英] Adding and subtract complex numbers using OOP structure
问题描述
我这里有一个代码,应该打印两个复数的和与差.给出的说明是:
将方法add
,subtract
和print
设置为void
和
使用构造函数的对象进行测试.
I have here a code that should print the sum and difference of two complex numbers. The instructions given are:
make the methods add
, subtract
, and print
to be void
and
test using the constructor's object.
public class Complex {
/**
* @param args
*/
public double real;
public double imag;
public String output = "";
public Complex(double real, double imag){
this.real += real;
this.imag += imag;
}
public Complex(){
real = 0;
imag = 0;
}
public double getReal(){
return real;
}
public void setReal(double real){
this.real = real;
}
public double getImag(){
return imag;
}
public void setImag(double imag){
this.imag = imag;
}
public void add(Complex num){
this.real = real + num.real;
this.imag = imag + num.imag;
}
public void subtract(Complex num){
this.real = real - num.real;
this.imag = imag - num.imag;
}
public void print(){
//
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Complex c1 = new Complex(4.0, 8.5);
Complex c2 = new Complex(8.0, 4.5);
c1.add(c2);
c1.subtract(c2);
c1.print(); //expected answer 12.0 + 13.0i
//-4.0 - 4.0i
}
}
预期的答案是12.0 + 13.0i和-4.0-4.0i.请使用方法print
帮助我.谢谢.
The expected answers are 12.0 + 13.0i and -4.0 - 4.0i. Please help me with the method print
. Thank you.
推荐答案
您错误地使用了打印方法.如果要查看正确的结果,则需要重写如下的add方法:
You incorrectly use print merhod. if you want to see correct result you need to rewrite add method like this:
public void add(Complex num, Complex num2){
this.real = num.real + num2.real;
this.imag = num.imag + num2.imag;
}
也重写减法.
public void subtract(Complex num){
this.real = real - num.real;
this.imag = imag - num.imag;
}
现在主要方法如下:
public static void main(String[] args) {
Complex c1 = new Complex(4.0, 8.5);
Complex c2 = new Complex(8.0, 4.5);
Complex result = new Complex(8.0, 4.5);
result.add(c1,c2);
result.print();
result.subtract(c1,c2);
result.print();
我以前说过的
print方法看起来像:
print method as I told previously look like:
public void print(){
System.out.println(real + " " + imag +"i");
}
说明:
您的代码中有错误.您将c2加到c1,然后减去c2 frim c1,然后打印结果.数学上看起来像是:c1 = c1 + c2-c2;
In your code you have error. You add c2 to c1 and then subtract c2 frim c1 and then print result. Mathematically this looks like : c1= c1+c2-c2;
这篇关于使用OOP结构增加和减少复数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!