我今天的目标是能够对复数 (a+bi) 进行加减乘除,并以某种方式显示该数据。当我尝试创建一种除复数的方法时,我知道困难会出现。如果我的数学正确或 ((29-11i)/74),它应该显示大约 0.39189-.1486i。我得到的输出是:-0.041666666666666664+0.4583333333333333i,这是不正确的。
你能帮我找出 ComplexDiv 方法中的错误吗?
代码如下:
public String ComplexDiv(ComplexNumbers other) {
String r = Double.toString(((real*other.real)-(complex*other.complex))
/ ((other.real * other.real)-(other.complex * other.complex)));
String c = Double.toString((-(real*other.complex)+(other.real*complex))
/ ((other.real * other.real)-(other.complex * other.complex)));
return r + "+" + c + "i";
}
这是调用该方法的测试类:
public class ComplexTest {
public static void main(String[] args) {
ComplexNumbers c1 = new ComplexNumbers();
ComplexNumbers c2 = new ComplexNumbers();
c1.real = 3;
c1.complex = 2;
c2.real = 5;
c2.complex = 7;
System.out.println(c1.ComplexAdd(c2));
System.out.println(c1.ComplexSub(c2));
System.out.println(c1.ComplexMult(c2));
System.out.println(c1.ComplexDiv(c2));
System.out.println(c1.findConjugate());
}
}
奖励问题:知道如何用分数形式而不是小数形式表示我的答案吗?
这里是整个 ComplexNumbers 类,只是为了让您大致了解我的方法:
package exerciseslearningjava;
public class ComplexNumbers {
public double real;
public double complex;
public double realConvert;
public double compConvert;
public String ComplexAdd(ComplexNumbers other) {
String r = Double.toString(real + other.real);
String c = Double.toString(complex + other.complex);
return r + "+" + c + "i";
}
public String ComplexSub(ComplexNumbers other) {
String r = Double.toString(real - other.real);
String c = Double.toString(complex - other.complex);
return r + c + "i";
}
public String ComplexMult(ComplexNumbers other) {
String r = Double.toString((real * other.real) - (complex*other.complex));
String c = Double.toString((real * other.complex)+(complex*other.real));
return r + "+" + c + "i";
}
public String ComplexDiv(ComplexNumbers other) {
String r = Double.toString(((real*other.real)-(complex*other.complex))
/ ((other.real * other.real)-(other.complex * other.complex)));
String c = Double.toString((-(real*other.complex)+(other.real*complex))
/ ((other.real * other.real)-(other.complex * other.complex)));
return r + "+" + c + "i";
}
public String findConjugate() {
String r = Double.toString(real);
String c = Double.toString(complex);
return r + "-" + c + "i";
}
}
最佳答案
你的分母:
((other.real * other.real) - (other.complex * other.complex))
不应该是:
((other.real * other.real) + (other.complex * other.complex))
由于您是通过将复数乘以其共轭得到的:
(a + bi) * (a - bi) = (a * a) - (b * b * i * i)
但是因为 i * i
是 -1,这变成了:
(a + bi) * (a - bi) = (a * a) + (b * b)
另外,顺便说一句,当我看到字符串被用来表示数值时,我的后脑勺都会有不好的感觉。为什么要使用字符串?为什么不是 float 或 BigDecimal?
关于java - 在java中显示复数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27240940/