我曾经在 case 语句中检查 int 值,但是有没有办法也检查 double 值?我无法使用 If else。这是一个任务。谢谢。
最佳答案
自 double
仅当该值可以表示为彼此“足够接近”(在尾数长度内)的 2 的幂之和时,值才提供精确的表示,并且因为 switch
仅适用于完全匹配,不能使用 double
一般情况下是在开关中。
其基本原因与使用==
时需要小心相同。比较double
s。解决方案也是相同的:您应该使用 if
链-then
-else
语句来查找所需的值
if (a <= 0.2) {
...
} else if (a < 0.5) {
...
} else if (a < 0.9) {
...
} else {
...
}
或使用 TreeMap<Double,Something>
并执行限制搜索:
TreeMap<Double,Integer> limits = new TreeMap<Double,Integer>();
limits.put(0.2, 1);
limits.put(0.5, 2);
limits.put(0.9, 3);
...
Map.Entry<Double,Integer> e = limits.ceilingEntry(a);
if (e != null) {
switch(e.getValue()) {
case 1: ... break;
case 2: ... break;
case 3: ... break;
}
}
关于java - 如何在java中的case语句中输入Double值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28588225/