给定两个double值,返回这些值之间的整数计数(包括那些值)。第二个参数将始终大于第一个参数。
intsBetween(3.5,4.5)→1
intsBetween(2.9,4.1)→2
intsBetween(3.0,4.0)→2
int intsBetween(double num1, double num2) {
num1 = Math.ceil(num1);
num2 = Math.ceil(num2);
int numBer = (int) (num2-num1);
if (num2-num1 == 1 )
numBer++;
return numBer;
}
不确定我错在哪里。 Results of Code
From To Expected Actual
3.5 4.5 1 2
2.9 4.1 2 2
3.0 4.0 2 2
.3 .9 0 0
165.0 170.0 6 5
0.0 6.8 7 7
0.001 0.999 0 0
答案 0 :(得分:1)
您需要获取第一个数字的上限和第二个数字的下限才能获得适当的范围。
public class DoubleRange {
public static void main(String[] args) {
DoubleRange doubleRange = new DoubleRange();
System.out.println(doubleRange.intsBetween(3.5D, 4.5D));
System.out.println(doubleRange.intsBetween(165D, 170D));
}
public int intsBetween(double num1, double num2) {
num1 = Math.ceil(num1);
num2 = Math.floor(num2);
return (int) num2 - (int) num1 + 1;
}
}
答案 1 :(得分:1)
我被IntStream
概念所吸引,所以我决定尝试一下。我使用了以下代码:
import static org.junit.Assert.*;
import java.util.stream.IntStream;
import org.junit.Test;
public class TestIntsBetween {
public static int intsBetweenStream(final double num1, final double num2) {
int below = (int)Math.ceil(num1);
int above = (int)Math.floor(num2);
return (int)IntStream.range(below, above)
.count() + 1;
}
public static int intsBetweenStreamCorrect(final double num1, final double num2) {
int below = (int)Math.ceil(num1);
int above = (int)Math.floor(num2);
return below < above
?(int)IntStream.range(below, above).count() + 1
: below == above
? 1
: 0;
}
public static int intsBetween(final double num1, final double num2) {
int below = (int)Math.ceil(num1);
int above = (int)Math.floor(num2);
return above - below + 1;
}
@Test
public void try_3_5___4_5 () {
int actual = intsBetween(3.5, 4.5);
assertEquals(1, actual);
}
@Test
public void try_2_9___4_1 () {
int actual = intsBetween(2.9, 4.1);
assertEquals(2, actual);
}
@Test
public void try_3_0___4_0 () {
int actual = intsBetween(3.0, 4.0);
assertEquals(2, actual);
}
@Test
public void try_0_3___0_9 () {
int actual = intsBetween(0.3, 0.9);
assertEquals(0, actual);
}
@Test
public void try_165_0___170_0 () {
int actual = intsBetween(165.0, 170.0);
assertEquals(6, actual);
}
@Test
public void try_0_0___6_8 () {
int actual = intsBetween(0.0, 6.8);
assertEquals(7, actual);
}
@Test
public void try_0_001___0_999 () {
int actual = intsBetween(0.001, 0.999);
assertEquals(0, actual);
}
}
正如预期的那样,简单的做法,从鞋面的地板上减去下限的天花板,然后加1,就像一个魅力。
然而,IntStream
方法未通过一些测试,特别是对(0.001,0.999)和(0.3,0.9)。这是因为流在每个范围中生成零整数,而减法方法生成-1。
可以更正此故障,如intsBetweenStreamCorrect
中所示。