gpt4 book ai didi

java - 我不断收到此错误: error: incompatible types: possible lossy conversion from double to int

转载 作者:行者123 更新时间:2023-12-03 08:48:49 24 4
gpt4 key购买 nike

我收到一个带有十进制整数的小箭头的错误。可以使用小数吗?我必须写些什么才能使小数可接受?这是我的代码:

public class BinarySearch {
public static final int NOT_FOUND = -1;

public static int search(int[] arr, int searchValue) {
int left = 0;
int right = arr.length - 1;
return binarySearch(arr, searchValue, left, right);
}

private static int binarySearch(int[] arr, int searchValue, int left, int right) {
if (right < left) {
return NOT_FOUND;
}

int mid = (left + right) >>> 1;
if (searchValue > arr[mid]) {
return binarySearch(arr, searchValue, mid + 1, right);
} else if (searchValue < arr[mid]) {
return binarySearch(arr, searchValue, left, mid - 1);
} else {
return mid;
}
}
}

import java.util.Arrays;

public class BinarySearchTest {

public static void main(String[] args) {
int[] arr = {-3, 10, 5, 24, 45.3, 10.5};
Arrays.sort(arr);
System.out.println(BinarySearch.search(arr, 2));
}
}

错误是这样的:

9:错误:类型不兼容:可能从 double 有损转换为整数
int [] arr = {-3,10,5,24,45.3,10.5};
^
9:错误:类型不兼容:可能从 double 有损转换为整数
int [] arr = {-3,10,5,24,45.3,10.5};
^
2个错误

最佳答案

线

int[] arr = {-3, 10, 5, 24, 45.3, 10.5};

主要是创建一个 double 数组(例如10.5),然后将其转换为int []。如果将类型更改为double [],则一切正常。这些是要更改的行:
public static int search(int[] arr, int searchValue) {

private static int binarySearch(int[] arr, int searchValue, int left, int right)

int[] arr = {-3, 10, 5, 24, 45.3, 10.5};

关于java - 我不断收到此错误: error: incompatible types: possible lossy conversion from double to int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47024099/

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