平方数 Java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36688675/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 01:45:44  来源:igfitidea点击:

square numbers Java

javasquare-root

提问by laish138

"An array is used to store ten integer numbers. Write a Java program that determines and print the square numbers which are also odd numbers from the given array."

“一个数组用于存储十个整数。编写一个 Java 程序来确定和打印平方数,这些平方数也是给定数组中的奇数。”

The problem I have is how to figure out if the number in the array is a square number. I tried this way but it's not correct!

我遇到的问题是如何确定数组中的数字是否为平方数。我试过这种方式,但它不正确!

import java.math.*;
public class JavaApplication43 {

    public static void main(String[] args) {

        int[] no = {22, 44, 25, 89, 81, 55, 23, 25, 55};

        for (int i = 0; i < no.length; i++) {

            int x = no[i];
            double y;
            if (x % 2 != 0) {
                y = Math.sqrt(x);
                if (x == (Math.pow(y, 2))) 
                    System.out.println(no[i]);
            }
       }
   }
}

This is the output it gives me

这是它给我的输出

run:
25
81
55
25
55

55is there too that means this method I used is not successful!

55是不是也就是我用的这个方法不成功!

回答by Konstantin Yovkov

You could just do:

你可以这样做:

for (int i = 0; i < no.length; i++) {
    int x = no[i];
    if (x % 2 == 0) continue;
    int y = (int) Math.sqrt(x);
    if (x == y * y) { 
        System.out.println(x);
    }
}

回答by Peter Lawrey

You can determine if a number is a square by checking if its square root is an integer.

您可以通过检查数字的平方根是否为整数来确定数字是否为正方形。

double sqrt = Math.sqrt(x);
long sqrt2 = Math.round(sqrt);
if (Math.abs(sqrt - sqrt2) / sqrt < 1e-15)
   // we have a square.

If you know xis an intyou shouldn't get a rounding error and you can do

如果你知道x是一个,int你不应该得到一个舍入错误,你可以这样做

int x = ...
double sqrt = Math.sqrt(x);
if ((int) sqrt == sqrt)
    // we have a square.

回答by Isuru

hope this will be much easier,

希望这会容易得多,

    if((arr[i]%2 != 0) & (Math.sqrt(arr[i])%1 == 0)){
        System.out.println(arr[i]);
    }

In here inside if condition first I check whether number is an odd number by taking modulus division and the 2nd condition check whether number is a perfect square. First I get the square root of given number and then take the modulus division by 1 and check whether it's equal to 0. If number is a perfect square, square root of that number is an integer, when I take the modulus division of an integer answer should be equal to 0.

在这里,如果条件首先我通过取模除法检查数字是否为奇数,第二个条件检查数字是否为完全平方数。首先我得到给定数的平方根,然后取模数除以 1 并检查它是否等于 0。如果数是完全平方数,则该数的平方根是整数,当我取整数的模数除法时答案应该等于 0。