【发布时间】:2016-02-16 00:12:57
【问题描述】:
我正在尝试编写一个程序,该程序将接受两个用户输入的数字,然后根据它们执行计算,但我想使用 if 语句来检查它是否试图除以零或输出将是无穷大.
import java.util.Scanner;
public class work {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double a, b, c, d;
System.out.printf("Enter the first number:");
a = scan.nextDouble();
System.out.printf("Enter the second number:");
b = scan.nextDouble();
/* various calculations */
c = a / b;
d = b / a;
if (a > 0)
{
System.out.printf("a/b = %.2f\n", c);
}
if (b > 0)
{ System.out.printf("b/a = %.2f\n", d);
}
else if (a <= 0)
{ System.out.printf("a/b = %.1f\n", d);
if (b > 0)
System.out.printf("a/b = INF\n");
}
}
}
例如,如果我输入 4 和 5,它最终会是这样的:
Enter the first number: 4
Enter the second number: 5
a/b = 0.80
b/a = 1.25
但是我无法让它检查零,并最终得到很多奇怪的输出。我怎样才能得到这样的输出?
------ Sample run 2:
Enter the first number: 0
Enter the second number: 4
a/b = 0.0
b/a = INF
------ Sample run 3:
Enter the first number: 4
Enter the second number: 0
a/b = INF
b/a = 0.0
------ Sample run 4:
Enter the first number: 0
Enter the second number: 0
a/b = INF
b/a = INF
【问题讨论】:
-
你得到了什么奇怪的输出?
-
您正在执行数学运算,然后检查它是否为
<= 0。首先检查它不是0并且只是iff它没有执行除法。
标签: java if-statement divide-by-zero infinity