2013-03-21 72 views
0

我在下面給出了這個問題,但是無論我採取什麼方法,我都無法通過所有測試。任何人都可以指出我要出錯的地方嗎?JAVA - 找出差異

該問題必須使用Math.abs()和IF語句解決,無需使用循環/函數等。

////////////////////////////// PROBLEM STATEMENT ////////////////////////////// 
// Given three ints, a b c, print true if one of b or c is "close"   // 
// (differing from a by at most 1), while the other is "far", differing  // 
// from both other values by 2 or more. Note: Math.abs(num) computes the  // 
// absolute value of a number.            // 
// 1, 2, 10 -> true              // 
// 1, 2, 3 -> false              // 
// 4, 1, 3 -> true               // 
/////////////////////////////////////////////////////////////////////////////// 

我的代碼:

if ((Math.abs(a-b) <= 1 || Math.abs(a+b) <= 1) && (Math.abs(a-c) >= 2 || Math.abs(a+c) >= 2)) { 

    if (Math.abs(a-c) >= 2 || Math.abs(a+c) >= 2) { 
     System.out.println("true"); 
    } else { 
     System.out.println("false"); 
    } 

    } else if (Math.abs(a-c) <= 1 || Math.abs(a+c) <= 1) { 

    if (Math.abs(a-b) >= 2 || Math.abs(a+b) >= 2) { 
     System.out.println("true"); 
    } else { 
     System.out.println("false"); 
    } 

    } else { 
    System.out.println("false"); 
    } 
+1

你想做些什麼? Math.abs()將始終返回> = 0。 – 2013-03-21 08:42:59

+1

你的正面案例是錯誤的;你需要兩個值之間的差異,但是當差異是3時,Math.abs(a + b)將返回最後一個場景的5。你想要abs(b-a)並且同樣適用於所有檢查。 – 2013-03-21 08:46:46

+0

@Bob謝謝你的一堆,我沒有接受,它使所有的差異! – AgentOrange 2013-03-21 13:50:53

回答

1

似乎過於複雜,你可能會想要去的東西更簡單:

boolean abIsClose = Math.abs(a-b) <= 1; 
boolean acIsClose = Math.abs(a-c) <= 1; 
boolean bcIsClose = Math.abs(b-c) <= 1; 
boolean result = abIsClose && !acIsClose && !bcIsClose; 
result = result || (!abIsClose && acIsClose && !bcIsClose); 
result = result || (!abIsClose && !acIsClose && bcIsClose); 

阿布斯總是給人一種正數,這樣,你不」 t需要確認一個值在-1和1之間,則只需確認< = 1.

+0

你不檢查另一個與接近的「遠」,所以'!cIsCose'證明'c'必須「遠離」,但它不能證明'c'遠離' B'。 – 2013-03-21 08:56:34

+0

@Chris我犯了同樣的錯誤,誤解了這個問題,它確實提到了比較兩者。 「,而另一個是」遠「,不同於**其他值** 2或更多」 – AgentOrange 2013-03-21 13:53:44

+0

@AgentOrange請參閱修訂後的代碼,現在成功僅基於三個關係中的一個關係緊密,另外兩個不關聯正在接近。 – 2013-03-21 16:02:08

0

,您可以將其分爲兩種可能的情況時,它的true

  1. b接近和c遠遠
  2. c接近和b遠遠

現在,是什麼1是什麼意思?

  • b接近 - Math.abs(a-b) <= 1
  • c遠 - Math.abs(a-c) >= 2 && Math.abs(b-c) >= 2

所以我們最終

if (Math.abs(a - b) <= 1 && Math.abs(a - c) >= 2 && Math.abs(b - c) >= 2) { 
    return true; 
} 

現在應用相同的邏輯來第二個條件:

if (Math.abs(a - c) <= 1 && Math.abs(a - b) >= 2 && Math.abs(b - c) >= 2) { 
    return true; 
} 

所以最終的方法是這樣的:

public static boolean myMethod(int a, int b, int c) { 
    if (Math.abs(a - b) <= 1 && Math.abs(a - c) >= 2 && Math.abs(b - c) >= 2) { 
     return true; 
    } 
    if (Math.abs(a - c) <= 1 && Math.abs(a - b) >= 2 && Math.abs(b - c) >= 2) { 
     return true; 
    } 
    return false; 
} 

輸出:

public static void main(String[] args) { 
    System.out.println(myMethod(1, 2, 10)); 
    System.out.println(myMethod(1, 2, 3)); 
    System.out.println(myMethod(4, 1, 3)); 
} 
true 
false 
true