使用 Java 数学平方根法计算 1 到 1,000 的平方根。然后只输出整数

Use the Java Math square root method to calculate square roots from 1 to 1,000. Then output the whole numbers only

Use the Java Math square root method to calculate square roots from 1 to 1,000. The output the whole numbers only.Do not start by calculating squares and then printing out that number's square root. Calculate all square roots and determine if they are whole numbers.

我查找了几个似乎围绕解决方案跳舞的答案,但其中 none 非常简洁。这是我目前所拥有的。

public class Assignment9
{
    public static void main(String[] args)
    {
        double root = 1;
        double sqrt = Math.sqrt(root);

        do
        {
            if(sqrt % 1 == 0)
            {
                System.out.printf("%.0f\t%.0f%n", root, Math.sqrt(root));
                root++;
            }
        }
        while(root <= 1000);
    }
}

输出正在打印平方根,但不断向上舍入每个数字。我只想为每个完美正方形打印一个数字(例如 1 1、4 2、9 3 等)。 我理解这个问题,但每次我 运行 程序我都会得到这个作为我的输出:

     1 1
     2 1
     3 2
     4 2
     5 2
     6 2
     7 3
     8 3
     9 3
     10 3
     ...
     1000 32

您没有更新值 sqrt。它始终只有 1,因此 sqrt % 1 始终为 0。

既然这显然是一个作业,我宁愿给出一些提示而不是解决方案。

需要思考的要点:

  • 想想sqrt是如何在循环中更新的。
  • 每当 sqrt % 1 == 0 为假时,root 会发生什么(以及它如何影响循环?)

要点:

  • 你真的需要 root 成为替身吗?