有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java平方数

我不明白为什么输出是25,因为我的错误理解,显然,我认为它是20,因为:第一个循环将是:i = 2; x = 5,并且自i <= m之后将有4个循环,因此5 x 4 = 20。我知道我错了,但不知道在哪里

public class num {
    public static void main(String[] args) {

       int m, x, i;

        x = 0;
        i = 1;
        m = 5;

        while (i<= m){
            x = x + m;
            i = i + 1;

        }
        System.out.println(x);
    }
}

共 (2) 个答案

  1. # 1 楼答案

    如果遇到这种情况,请尝试调试和打印。大多数时候,你会发现你的answqer:

    public class num {
        public static void main(String[] args) {
            int m, x, i;
    
            x = 0;
            i = 1;
            m = 5;
    
            System.out.println("Initial : x = " + x + " and i = " + i);
    
            while (i <= m) {
                x = x + m;
                i = i + 1;
                System.out.println("x = " + x + " and i = " + i);
            }
            System.out.println(x);
        }
    }
    

    输出:

    Initial : x = 0 and i = 1
    x = 5 and i = 2
    x = 10 and i = 3
    x = 15 and i = 4
    x = 20 and i = 5
    x = 25 and i = 6
    25
    
  2. # 2 楼答案

    让我们试着试一试:

    x=0;i=1;m=5
    while (1<=5) ? yes, so x=0+5; i=2,
    while (2<=5) ? yes, so x=5+5; i=3,
    while (3<=5) ? yes, so x=10+5; i=4,
    while (4<=5) ? yes, so x=15+5; i=5,
    while (5<=5) ? yes, so x=20+5; i=6,
    while (6<=5) ? no, so exit from loop
    

    因此结果是:x=25