如果结果等于 NaN 或 -infinity,我无法找到一种方法来捕获或命令我的程序。 每当我在我的程序中输入 0 时,它都会给我一个 NaN 和 -Infinity 的结果。 我面临的问题是 x1 和 x2 是 double 类型,显然无法与 String 类型进行比较。任何帮助将不胜感激。
public class Exercise {
public static void main(String[] args){
double x1 = 0;
double x2 = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("Feed me with a, b and c");
try{
double a = scanner.nextDouble();
double b = scanner.nextDouble();
double c = scanner.nextDouble();
scanner.close();
double discriminant = (b * b) - 4 * (a * c);
if (discriminant > 0){
x1 = (-b + Math.sqrt(discriminant)) / (2 * a);
x2 = (-b - Math.sqrt(discriminant)) / (2 * a);
System.out.println("The dish of yours has two components " + x1
+ " and " + x2);
}
if (discriminant == 0){
x1 = -b / (2 * a);
System.out.println("The dish of yours has two identical
components " + x1 +" and " + x1);
}
if (discriminant < 0){
System.out.println("The dish of yours doesn't have any
component");
}
}
catch (InputMismatchException e) {
System.out.println("I can't digest letters");
}
catch (Exception e) {
System.out.println("This is inedible");
}
}
}
最佳答案
您可以通过以下方式检查 NaN
if (Double.isNaN(yourResult)) { ... }
通过做无限:
if (Double.isInfinite(yourResult)) { ... }
您永远不应该使用 ==
来检查 NaN
,因为 NaN
被认为不等于 NaN
!
或者,您可以只检查 a
是否为 0。因为这可能是唯一会出现 Infinity 和 NaN 的情况。如果是,请说“Where's my a dish?”之类的话。 :)
此外,我刚刚尝试输入 Nan NaN NaN
,但它没有输出任何内容。考虑检查 a、b 和 c 是否也为 NaN 或 Infinities。 :)
关于java NaN 和 -infinity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48921978/