【问题标题】:Why is the number 30 not displayed at the end of the output? [closed]为什么输出末尾没有显示数字 30? [关闭]
【发布时间】:2021-11-29 21:11:34
【问题描述】:

enter image description here

package com.company;

public class Main {

    public static void main(String[] args) {
        // write your code here
        int p=0;

        for (int i=1; i<11; i++)
        {
            if (i%2 == 0)
            {
                System.out.println(p);
                p = p + i;
            }
        }
    }
}

【问题讨论】:

  • 打印在添加之前,不打印p的最终值。

标签: java android for-loop intellij-idea output


【解决方案1】:

循环之后添加一个打印。您也可以从2 开始。并为每次迭代增加2(从而消除模二测试的需要)。类似的,

int p = 0;
for (int i = 2; i < 11; i += 2) {
    System.out.println(p);
    p += i;
}
System.out.println(p);

哪些输出

0
2
6
12
20
30

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多