简体   繁体   English

我在这个 for 循环示例中遇到了困难

[英]I'm having a tough time with this for loop example

The method evenSquares takes a single int parameter, n, (for example, 10000), and then prints all of the (positive) even perfect squares less than n, each on a separate line.方法evenSquares接受单个 int 参数 n(例如,10000),然后打印所有小于 n 的(正)偶数完全平方数,每个都在单独的行上。

Notice that evenSquares has a void return type, since all it does is print integers to the console.请注意, evenSquares 有一个 void 返回类型,因为它所做的只是将整数打印到控制台。 Be sure to use the println method to print each entry of your output.请务必使用println方法打印输出的每个条目。

Example: if n = 40, your code should print:

4
16
36

(Hint: your method should be built around a for loop with a test component that asks if the square of the control variable (say, k) is < n. Thus, the loop should terminate as soon as k*k equals or exceeds n.) (提示:您的方法应该围绕一个带有测试组件的 for 循环构建,该组件询问控制变量(比如 k)的平方是否 < n。因此,只要 k*k 等于或超过 n,循环就应该终止.)

I'm given this我得到了这个

public void evenSquares(int n) {
public class Squares {

    public static void main(String[] args) {        
        evenSquares(40);
    }

    public static void evenSquares(int n) {
        for(int sq, k=2; (sq = k*k) <= n ; k += 2){
            System.out.println(sq);
        }
    }

}

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

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