为什么写出来 控制台中的根是NaN和NaN?我读过有关NaN的,但我没有找到合适的解决方案,我怎么能修复的错误......我已经试过铸造翻番的判别和根源,但不起作用.有人可以帮助我,在哪里以及我需要重写什么?
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
Pattern newlineOrSpace = Pattern.compile(System
.getProperty("line.separator")
+ "|\\s");
sc.useDelimiter(newlineOrSpace);
System.out.print("Enter a, b, c: ");
double a = sc.nextDouble();
double b = sc.nextDouble();
double c = sc.nextDouble();
// System.out.format("a = %f, b = %f, c = %f", a, b, c);
double root1;
double root2;
double discriminant;
discriminant = Math.sqrt(b * b - 4 * a * c);
if (discriminant > 0) {
System.out.println("There are no real roots ");
} else {
root1 = (-b + discriminant) / (2 * a);
root2 = (-b - discriminant) / (2 * a);
System.out.println("The roots are " + root1 + " and " + root2);
}
Run Code Online (Sandbox Code Playgroud)
Math.sqrt(x)NaN当x为负时返回,然后通过其余代码传播.在获取平方根之前,您需要测试负数:
discriminant = b * b - 4 * a * c;
if (discriminant < 0) {
System.out.println("There are no real roots ");
} else {
root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
System.out.println("The roots are " + root1 + " and " + root2);
}
Run Code Online (Sandbox Code Playgroud)
首先,让我们摆脱用户输入作为原因 - 如果简短但完整的程序包含我们需要的所有数据,则会更容易:
public class Test {
public static void main(String args[]) {
showRoots(2.0, 10.0, 2.0);
showRoots(10.0, 1.0, 1.0);
}
private static void showRoots(double a, double b, double c) {
double discriminant = Math.sqrt(b * b - 4 * a * c);
if (discriminant > 0) {
System.out.println("There are no real roots ");
} else {
double root1 = (-b + discriminant) / (2 * a);
double root2 = (-b - discriminant) / (2 * a);
System.out.println("The roots are " + root1 + " and " + root2);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这显示了两个案例 - 一个确实存在根源的案例 - 但程序声称没有 - 而且其中一个确实没有真正的根,但程序将它们打印为NaN.当你取负数的平方根时,结果是NaN,这就是显示它的原因.
所以,问题在于你如何处理判别式问题.如果b 2 - 4ac是非负的,那么就有了真正的根源- 但是你已经在那个时候采用了平方根并扭转了条件的性质.
所以,它应该是:
private static void showRoots(double a, double b, double c) {
double discriminant = b * b - 4 * a * c;
if (discriminant < 0) {
System.out.println("There are no real roots ");
} else {
double discriminantRoot = Math.sqrt(discriminant);
double root1 = (-b + discriminantRoot) / (2 * a);
double root2 = (-b - discriminantRoot) / (2 * a);
System.out.println("The roots are " + root1 + " and " + root2);
}
}
Run Code Online (Sandbox Code Playgroud)
经验教训:
编辑:正如评论中所指出的,还有各种特殊情况需要考虑,包括何时a为0,否则将导致除以0问题.