gpt4 book ai didi

java - 不兼容的类型 : possible lossy conversion from long to int While using if condition

转载 作者:行者123 更新时间:2023-12-02 03:03:44 25 4
gpt4 key购买 nike

/**
*
* @param b is an array
* @param x is the element for which I want to search the lower bound
* @param n is the length of the array
* @return high if element not found or mid - 1 if found
*/

static long searchMe(long b[], long x, long n){
long low = 0, high = n, mid=0;
while(low<=high){
mid = (low+high)/2;
if(b[mid] == x){
if(mid > 0 && b[mid-1] == x) high = mid-1;
else return mid-1;
}
else if(b[mid] < x) low = mid + 1;
else high = mid - 1;
}
// System.out.println(low + " == " + high);
return high;
}

最佳答案

您使用 mid 作为数组的索引,但 mid 很长。数组的索引始终是 int。你可以试试这个。

static long searchMe(long b[], long x, long n) {
long low = 0, high = n;
int mid = 0; // CHANGED FROM long TO int
while (low <= high) {
mid = (int) ((low + high) / 2); // CAST to int
if (b[mid] == x) {
if (mid > 0 && b[mid - 1] == x)
high = mid - 1;
else
return mid - 1;
} else if (b[mid] < x)
low = mid + 1;
else
high = mid - 1;
}
// System.out.println(low + " == " + high);
return high;
}

关于java - 不兼容的类型 : possible lossy conversion from long to int While using if condition,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57035535/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com