本文介绍了为什么二次方程式的根结果是NaN? (Java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么要写出来根源是控制台中的NaN和NaN 吗?我已经读过有关NaN的文章,但是我找不到合适的解决方案,该如何解决错误...我已经尝试过广播,将判别和根加倍,但是不起作用.有人可以帮助我,在什么地方以及我需要重写什么?
Why write out The roots are NaN and NaN in console?I've read about NaN, but I don't find the right solution how can I repair the mistakes...I've tried casting to double the discriminant and the roots but doesn't work.Can somebody help me, where and what I need to rewrite?
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);
}
推荐答案
Math.sqrt(x)
当x
为负数时返回NaN
,然后在其余代码中传播.您需要测试之前取平方根的负数:
Math.sqrt(x)
returns NaN
when x
is negative, which then propagates through the rest of your code. You'll want to test for negative numbers before taking the square root:
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);
}
这篇关于为什么二次方程式的根结果是NaN? (Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!