<分区>
如何修改我所写的内容以指定用户输入的数字是否为完全正方形?
我试过放置各种 % 展示位置,但无济于事。我在网上找到的解决方案没有使用我想要的 M.O。
我将包括一个我在网上找到的解决方案,具有讽刺意味的是,考虑到本书强调避免使用蛮力技术,我认为该解决方案效率低下,而且似乎没有产生预期的结果。
这个问题来自 Java 艺术与科学第 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);
}
}