【发布时间】:2020-11-02 23:36:30
【问题描述】:
所以,我编写了一个 Java 程序来找到二次方程的解,我的问题是我似乎无法编写正确的代码来找到“虚数”,当它打印出来时,我只得到“NaN”。有什么解决办法吗?
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the value for a: ");
double a = scan.nextDouble();
System.out.print("Enter the value for b: ");
double b = scan.nextDouble();
System.out.print("Enter the value for c: ");
double c = scan.nextDouble();
double result = b * b - 4.0 * a * c;
if(result > 0.0){
//to find two real solutions
double x1 = (-b + Math.pow(result, 0.5)) / (2.0 * a);
double x2 = (-b - Math.pow(result, 0.5)) / (2.0 * a);
System.out.println("There are two real solutions.");
System.out.println("x1 = " + x1);
System.out.println("x2 = " + x2);
//to find one real solution
} else if(result == 0.0){
double x1 = (-b / (2.0 * a));
System.out.println("There is one real solution");
System.out.println("x = " + x1);
//to find the imaginary numbers
} else if(result < 0.0){
double x1 = (-b + Math.pow(result, 0.5)) / (2.0 * a);
double x2 = (-b - Math.pow(result, 0.5)) / (2.0 * a);
System.out.println("There are two imaginary solutions.");
System.out.println("x1 = " + x1 + " + " + x2);
System.out.println("x2 = " + x1 + " - " + x2);
}
}
}
【问题讨论】:
-
你能添加一个你测试和预期输出的例子
-
顺便说一句,没有必要将
results提高到 0.5 次方。有一个Math.sqrt 方法。
标签: java numbers quadratic quadratic-programming repl.it