我试了很多,但只能说明南。 我不确定我做得对不对。
class Imaginary{
double a = 2;
double b = 3;
double c = 5;
double result = b * b - 4 * a * c;
if(result < 0.0){
double im1 = -2 + (Math.sqrt((result))/ 10);
double im2 = -2 - (Math.sqrt((result))/ 10);
System.out.println("x = " + imaginary1 + " or x = " + imaginary2);
}
}
您需要在取平方根之前先取negateresult
使其为正(取负数的平方根总是结果为NaN),并在打印之前追加“i”。
double real = -b / (2*a);
double img = Math.sqrt(-result) / (2*a);
System.out.println("x = " + real + " + " + img +"i or x = " + real + " - " + img + "i");
您不应该使用sqrt(result),因为它总是导致您取负数的平方根(这是您的result条件)。 相反,试着用一个公式(如完成正方形)。
希望它能回答你的问题:)
因为你有复数根,所以你需要用复数来解方程。 Java缺乏对复数的内置支持,但您可以使用Apache Commons:
if (result < 0.0) {
final Complex cb = new Complex(-b, 0.0);
final Complex root = new Complex(result, 0.0).sqrt();
final Complex r1 = cb.add(root).divide(2 * a);
final Complex r2 = cb.subtract(root).divide(2 * a);
}