我有一些像这样的代码:
class Foo {
public double x;
}
void test() {
Foo foo = new Foo();
// Is this a valid way to test for zero? 'x' hasn't been set to anything yet.
if (foo.x == 0) {
}
foo.x = 0.0;
// Will the same test be valid?
if (foo.x == 0) {
}
}
Run Code Online (Sandbox Code Playgroud)
我基本上希望将来避免被零除的例外.
谢谢
这个问题出现在这段代码之后(二进制搜索的实现).如果有人能告诉我为什么没有输出预期答案,我将不胜感激:
public static void main(String[] args){
Double[] array = {0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0};
BinarySearch s = new BinarySearch(array);
System.out.println(s.searchNextHighest(2.0));
}
public BinarySearch(Double[] array){
numbers = array;
}
public Integer searchNextHighest(Double y){
return binarySearchNextHighest(0, numbers.length-1, y, numbers);
}
public Integer binarySearchNextHighest(int min, int max, Double target, Double[] array){
int mid = (min+max)/2;
if(target==array[mid]){ //Fails here
return mid;
}
if(max<min){
if(min>=array.length) return null;
return mid;
}
if(target>array[mid]){
return binarySearchNextHighest(mid+1, max, target, array);
}else{
return binarySearchNextHighest(min, mid-1, target, array);
}
}
Run Code Online (Sandbox Code Playgroud)
输出:1
我跟着一个调试器并且绝对肯定.在某个时刻,target = 2.0,mid = …