2016-02-16 35 views
0

我想寫一個程序,將採取兩個用戶輸入數字,然後執行基於他們的計算,但我想使用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

你得到的奇怪輸出是什麼? –

+1

您正在執行數學計算,然後檢查它是否爲「<= 0」。首先檢查它是否不是「0」**和**只有***如果***不執行除法。 –

回答

1

似乎你在這裏有很多問題。你的第一個問題是你在決定是否解決方案是INF時檢查分子。例如,如果你輸入1和0,你的代碼檢查是否> 0(它是)並輸出1/0的c。你真正想要做的是檢查方程的支配者(在這種情況下是否等於零)。

看來你還忘記了第一個else語句,如果我不確定你在第二個if語句的else中是如何完成的。

您的第三個問題是您的代碼正在檢查變量是否小於0,而不是不等於0,這會導致任何負面輸入的意外結果。請記住,只有零值纔會導致答案未定義,或稱爲INF。無論如何,下面的代碼應該按照預期運行。請注意,我稍微修改了類名,以符合Java naming conventions

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.print("Enter the first number: "); 
    a = scan.nextDouble(); 

    System.out.print("Enter the second number: "); 
    b = scan.nextDouble(); 

    /* various calculations */ 
    c = a/b; 
    d = b/a; 


    if (b != 0) 
    { 
     System.out.printf("a/b = %.2f\n", c); /* the dominator (b) is not 
              zero, so the solution is a/b 
              (stored in the variable c) */ 
    } 
    else 
    { 
     System.out.print("a/b = INF\n"); /* the dominator (b) is zero, 
             so the solution is INF */ 
    } 

    if (a != 0) 
    { 
     System.out.print("b/a = %.2f\n", d); /* the dominator (a) is not 
              zero, so the solution is a/b 
              (stored in the variable d) */ 
    } 
    else 
    { 
     System.out.printf("b/a = INF\n"); /* the dominator (a) is zero, 
             so the solution is INF */ 
    } 
    } 
} 
+0

啊,我在這麼匆忙中犯了很多錯誤..非常感謝。 –

0

正如我注意到你正試圖從控制檯獲取一個整數爲雙。這可能會導致各種奇怪的產出。 因此將您的代碼更改爲

a = scan.nextInt(); 
b = scan.nextInt(); 

這應該可以正常工作。謝謝你

+0

謝謝,但我仍然有一個問題,試圖找出我需要告訴它何時打印INF或零。 –

+0

您應該在計算之前檢查零點,而不是之後。 – felipecrp

相關問題