我在下面給出了這個問題,但是無論我採取什麼方法,我都無法通過所有測試。任何人都可以指出我要出錯的地方嗎?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");
}
你想做些什麼? Math.abs()將始終返回> = 0。 – 2013-03-21 08:42:59
你的正面案例是錯誤的;你需要兩個值之間的差異,但是當差異是3時,Math.abs(a + b)將返回最後一個場景的5。你想要abs(b-a)並且同樣適用於所有檢查。 – 2013-03-21 08:46:46
@Bob謝謝你的一堆,我沒有接受,它使所有的差異! – AgentOrange 2013-03-21 13:50:53