简体   繁体   中英

How do I check if the values that I enter in an array are squared as the array continues?

This is my first time using this and I'm having a bit of trouble with arrays. I need to check if the values in an array that the user enters are continuously being squared such as {2, 4, 16, 256} . Checking if num[1] = num[0] * num[0], num[2] = num[1] * num[1] and so on. Any help would be appreciated.

import java.util.Scanner;

public class PS6Square {
    public static void main (String [] args){

        Scanner scan = new Scanner(System.in);
        System.out.println("How many values would you like to enter?");
        String input = scan.next();
        int array = Integer.parseInt(input);
        int num[] = new int[array];
        int i = 0;
        boolean result = false;

        for(i = 0; i < num.length; i++)
        {
            System.out.print("Enter a value:\t");
            num[i] = scan.nextInt();
            if(num[i] == num[i] * num[i])
            {
                result = true;
            }
        }

        System.out.println("\nThe result is:\t" + result);
    }
}

This question has already been asked. Try the search function next time.

But here is a solution:

 double sqrt = Math.sqrt(int_to_test);
 int x = (int) sqrt;
 if(Math.pow(sqrt,2) == Math.pow(x,2)){
 //it is a perfect square
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM