如何修改我所写的内容以指定用户输入的数字是否是完美的正方形?
我尝试过放置各种%的展示位置,但无济于事。我在网上找到的解决方案并没有使用我想要的M.O。
我将在网上找到一个解决方案,鉴于本书强调避免使用强力技术,我认为具有讽刺意味的是低效率,并且似乎无法产生预期的效果。
这个问题来自Java的Art And Science第5章,编号练习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);
}
}
以下是我认为缺乏的解决方案:
/*
* 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);
}
}
答案 0 :(得分:1)
要知道给定数字是否具有完美的平方根,您可以尝试如下所示 -
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");
}
因为,如果一个数字具有完美的平方根,那么数字本身就是一个完美的正方形。
这会有所帮助!