如果X在Y的3以内,那么它将是真的(需要一个if语句)。我试过:
import java.util.*;
import java.io.*;
public class e4 {
public static void main (String arg[]) {
if ( ( (x - 3) <= y ) || ( (x - 3) <= y) || (x >= (y -3) ) || (x >= (y -3) ))
{
System.out.println("Your are within 3 of each other!");
}
else
{
System.out.println("Your NOT within 3 of each other.");
}
} //end main
} //end class非常感谢您的帮助!
发布于 2013-10-29 22:08:50
使用一些更简单的方法:
if (Math.abs(x - y) < 3.0) {
// within 3
}发布于 2013-10-29 22:10:09
你不需要Math.abs。这样做。
if ( x >= y - 3 && x <= y + 3 )这里有一个例子,Math.abs给出了一个错误的答案,因为减法损失了小浮点数。如果准确性对您很重要,那么您应该避免使用Math.abs。
请注意,在我的解决方案中出现类似事情的示例是可能的;但是这样的示例很少,只有在x和y表示的“范围”包含的部分相差超过3,部分差小于3的情况下才会发生。
float x = - 0.2500001f;
float y = 2.75f;
System.out.println( x >= y - 3 && x <= y + 3 ); // Prints false (correct)
System.out.println( Math.abs(x-y) <= 3.0); // Prints true (wrong)https://stackoverflow.com/questions/19670090
复制相似问题