当使用 Math.sqrt() 作为参数时,列表包含方法 returns false

List contains method returns false when using Math.sqrt() as a parameter

我正在更新我在 Java 中的知识,并正在做一个代码战争的练习。问题是如果元素是 "same",则比较两个数组。 "same"的意思是'b'中的元素是'a'中的元素的平方,与顺序无关。我尝试做的解决方案是获取 'b' 中元素的平方根,并使用 Math.sqrt() 检查它是否存在于元素 'a' 中。但是,当我将它用作 contains() 的参数时,它总是 returns false.

因此,为了检查元素 'b' 的平方根是否确实存在于 'a' 中,我尝试了一个简单的 if-else 来检查特定元素。但是,当我将它与 Math.sqrt() 合并时,问题就出现了。

这是集合a和b的元素

int[] a = {121, 144, 19, 161, 19, 144, 19, 11};
int[] b = {121, 14641, 20736, 361, 25921, 361, 20736, 361};

我已经转换成List

List<Integer> setAList = Arrays.stream(setA)//int[] setA - parameter of a function
                                                    .boxed()
                                                    .collect(Collectors.toList());
List<Integer> setBList = Arrays.stream(setB)//int[] setB - parameter of a function
                                                    .boxed()
                                                    .collect(Collectors.toList());

我将数组转换为 List 以利用 contains() 方法。 这是我尝试检查特定元素时的代码

double sqrd = Math.sqrt(setBList.get(6));
return setAList.get(5) == sqrd ? true : false;

这给出了预期的结果 - 是的。 现在这是我将它合并到 for 循环中的代码

boolean same = true;

for(int indexB : setB) {
    same = setAList.contains(Math.sqrt(indexB)) ? true : false; 
    System.out.println(Math.sqrt(indexB) + " " + same);

}

这是结果

11.0 false
121.0 false
144.0 false
19.0 false
161.0 false
19.0 false
144.0 false
19.0 false
false

起初我虽然问题可能是因为数据类型,但我已经尝试将 double 转换为 int 但我仍然得到相同的结果。

setAList.get(5) == sqrd 给你预期的结果,因为 the widening primitive conversion of setAList.get(5)(这是一个 int)到 double.

如果您有 setAList.contains(Math.sqrt(indexB)),您需要手动进行转换:setAList.contains((int)Math.sqrt(indexB))

不是直接的答案,而是避免此类问题的解决方法:

如其他答案中所述,您的问题是转换问题,因为您必须处理 doubleint 值,而不必面对转换问题。

避免这种情况的一种方法是对 A 中的值求平方而不是计算 B 中的值的平方根。这样你就只会处理 int 个值

int[] a = {121, 144, 19, 161, 19, 144, 19, 11};
int[] b = {121, 14641, 20736, 361, 25921, 361, 20736, 361};

// Make a list containing the squares out of the b array
List<Integer> squares = Arrays.stream(b)
    .boxed()
    .collect(Collectors.toList());

// square all the values in B,
// and check that all the resultant values are present in the squares list
boolean same = Arrays.stream(a) // Stream<Integer> containing values in array a
    .map(i -> i* i) // Stream<Integer> containing values in array a squared
    .allMatch(squares::contains); // reduce to a boolean insuring that all values in the Stream<Integer> are present in the squares list

System.out.println(same);

查找 exact 浮点值,正如在 contains() 中所做的那样,由于浮点值的精度有限,在大多数情况下是一个坏主意;你可以自己试试,看看哪些数字 Math.sqrt( number ) * Math.sqrt( number )number:

not 相同
for (int i = 0; i < 100; i++) {
  final double r = Math.sqrt(i);
  final double s = r * r;
  if (s != i) {
    System.out.println(i + " != " + s);
  }
}

(在测试的 100 个数字中打印出 51 non-equal roots-squared。)