简体   繁体   English

使用Java Math平方根方法计算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. 使用Java Math平方根方法计算1到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. 计算所有平方根并确定它们是否为整数。

I looked up several answers that seemed to dance around the solution but none of them so very concise. 我查了几个似乎可以解决问题的答案,但没有一个非常简洁。 Here is what I have so far. 这是我到目前为止所拥有的。

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);
    }
}

The output is printing the square roots but keeps rounding up each number. 输出结果是打印平方根,但仍将每个数字四舍五入。 I want to only print out one number per perfect square, (eg 1 1, 4 2, 9 3, etc). 我只想在一个完美的正方形上打印一个数字(例如1 1、4 2、9 3等)。 I understand the question, but every time I run the program I get this as my output: 我理解这个问题,但是每次运行程序时,我都会得到以下结果:

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

You aren't updating the value sqrt. 您没有更新值sqrt。 It's always just 1, and thus sqrt % 1 is always 0. 它始终仅为1,因此sqrt%1始终为0。

Since this is obviously an assignment, I'd rather give some hints instead of the solution. 由于这显然是一项任务,因此我宁愿给出一些提示而不是解决方案。

Important points to think about: 要考虑的重点:

  • Think of how sqrt is updated in the loop. 考虑一下如何在循环中更新sqrt
  • Whenever sqrt % 1 == 0 is false, what happens to root (and how does it affect the loop?) 每当sqrt % 1 == 0为false时, root会发生什么(以及它如何影响循环?)

Minor points: 次要点:

  • Do you really need root to be a double? 您是否真的需要root才能成为双打?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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