How to indicate if a given number has an integer with a square root?

How do I change what I wrote to indicate if the user input number is an ideal square?

I tried to place different placements, but to no avail. The solutions I found on the Internet do not use the desire of MO

I will include one solution that I found on the Internet that I think is ironically ineffective given the book’s emphasis on preventing brute force methods and does not seem to produce the desired results.

This problem comes from the art and science of Java. Chapter 5, Programming Exercise No. 7.

/**
 * This program tells the user whether the number they've entered returns a perfect square. *
 */

import acm.program.*;
import java.lang.Math;

public class Squares extends ConsoleProgram {

    public void run() {
        println("This program determines whether the number you're about to enter is a perfect square");
        int s = readInt("Enter a positive number here: ");
        switch (s) {

        }

        if (isPerfectSquare(s)) {
            ;
        }
        {
            println((int) Math.sqrt(s));
        }
    }

    private boolean isPerfectSquare(int m) {
        int sqrt = (int) Math.sqrt(m);
        return (sqrt * sqrt == m);
    }
}

And here is a solution that I consider insufficient:

/*
 * File: PerfectSquare.java
 * -------------------------
 * This program test the isPerfectSquare(n) 
 * that returns true if the integer n is a 
 * perfect square.
 */
import acm.program.*;
import java.lang.Math;

public class Book extends ConsoleProgram {

    private static final int MIN_NUM = 1;
    private static final int MAX_NUM = 100000000;

    public void run() {
        int cnt = 0;
        for (int i = MIN_NUM; i <= MAX_NUM; i++) {
            if (isPerfectSquare(i)) {
                cnt++;
                println(cnt + ": " + (int) Math.sqrt(i) + ": " + i);
            }
        }
    }

    private boolean isPerfectSquare(int n) {
        int sqrt = (int) Math.sqrt(n);
        return (sqrt * sqrt == n);
    }
}
+4
source share
1 answer

, , , -

if((Math.sqrt(m))%1 == 0) {
   System.out.println("Number (m) has a Perfect Square-Root");
} else {
   System.out.println("Number (m) does not have a Perfect Square-Root");
}

, , .

!

+1

All Articles