简体   繁体   English

输入数字n,然后打印1到n之间的所有偶数平方

[英]Enter a number n, then prints all even squares between 1 and n

I need help figuring out on how to output even numbers between 1 and N (n is a number entered by the user). 我需要帮助弄清楚如何输出1到N之间的偶数(n是用户输入的数字)。

Here is what I have so far. 这是我到目前为止所拥有的。

import java.util.*;

public class HelloWorld{

     public static void main(String []args){
         int n;
         int i = 0;

        Scanner scan = new Scanner(System.in);
        System.out.println("Enter a Number");
        n = scan.nextInt();

        for(i=1; i<n; i++){
            if(i%2==0)
            i = i*i;
            System.out.println(i);
        }    
    }
}

Now that prints out the wrong output. 现在,将输出错误的输出。 I would like to know how it gets from 4 to 16 and to 36. 我想知道它如何从4变为16到36。

Sample Input: 45 样本输入: 45

Expected Output: 预期产量:

4
16
36

What is it that I'm doing wrong? 我做错了什么事?

You are already increasing the variable i in the for definition, you don't need to increase again inside for block. 您已经在for定义中增加了变量i ,不需要在for块中再次增加。 Also start from 2 and move on by adding 2 on each step for a more efficient implementation. 同样从2开始,然后在每个步骤上加2,以实现更高效的实现。

for(i=2; i*i<n; i+=2){
        System.out.println(i*i);
    }    

First, don't change the value of i inside the for loop. 首先,不要在for循环中更改i的值。 Instead of changing i to equal i*i , just print out i*i using the statement System.out.println(i*i) ; 不用将i更改为等于i*i ,只需使用语句System.out.println(i*i)打印出i*i Secondly, you also forgot the curly brackets after your if statement. 其次,您还忘记了if语句后的花括号。

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

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