2

我正在更新我在 Java 方面的知识,并在代码战中进行练习。问题是如果元素“相同”,则比较两个数组。“相同”的意思是'b'中的元素是'a'中的元素的平方,无论顺序如何。我试图做的解决方案是获取“b”中元素的平方根,并使用 Math.sqrt() 检查它是否存在于元素“a”中。但是,当我将它用作 contains() 的参数时,它总是返回 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<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 但我仍然得到相同的结果。

4

3 回答 3

2

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

正如其他答案中所解释的,您的问题是演员表问题,因为您必须处理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);
于 2019-06-14T12:58:44.527 回答
1

setAList.get(5) == sqrd由于(这是 a )到 a的原始转换扩大,因此为您提供了预期的结果。setAList.get(5)intdouble

如果你有setAList.contains(Math.sqrt(indexB)),你需要手动做演员:setAList.contains((int)Math.sqrt(indexB))

于 2019-06-14T12:40:05.607 回答
0

由于浮点值的精度有限,大多数时候查找精确的浮点值(如 中所做的)是一个坏主意;contains()您可以自己尝试一下,看看哪些数字与以下Math.sqrt( number ) * Math.sqrt( number )内容不同number

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 个不相等的平方根。)

于 2019-06-14T13:32:10.470 回答