我想寫一個程序,將採取兩個用戶輸入數字,然後執行基於他們的計算,但我想使用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」**和**只有***如果***不執行除法。 –