任何人都可以告诉我为什么我的外部for循环不会增加变量?

时间:2017-02-22 00:31:02

标签: java for-loop

我使用Eclipse,当我调试并逐步执行代码时,我的外部循环不会增加,并且根始终保持为2.任何人都可以告诉我为什么?最重要的评论解释了我想要完成的任务。

public class First_120_Numbers {
    /*A Leyland number sequence is a series of numbers of the formxy + yxwhere x and y are integers greater than 1.    
     * They are named after the mathematician Paul Leyland. The first few Leyland numbers are  
     *8, 17, 32, 54, 57, 100, 145, 177, 320, 368, …
     *Take 145 as an example where it is x^y+y^x = 34+43
     *By considering the terms in the Leyland sequence find the sum of the first 20 numbers in the Leyland sequence.*/
    public static void main(String[] args) {
        double root, expo, prodX, prodY, leySum1 = 0, leySum2 = 0;
        root = 2; // Leyland numbers must be greater than 1
        expo = 2;
        for (; root <= 20; root++) {
            for (; expo <= 20; expo++) {
                prodX = Math.pow(root, expo); //raises root to expo
                prodY = Math.pow(expo, root);// raises expo to root
                leySum1 = prodX + prodY;
                leySum2 += leySum1;
                System.out.println(leySum1);
            }
        }
        System.out.println("The sum of the leyland numbers " 
                + "up to 20 is " + leySum2);
    }
}

2 个答案:

答案 0 :(得分:1)

你不正确。 root变量每次都会递增,但我猜你每次外循环迭代都忘记初始化变量expo

试想一下,当外部循环完成第一次迭代(root = 2)时,expo的值变为21,因为你没有再次将它初始化为2,所以内部循环没有执行对于外循环的其余迭代。

为了更好地理解以下代码片段,请看看会发生什么!

for (root = 2; root <= 20; root++) {
    System.out.print(root + " --> ");
    for (expo = 2; expo <= 20; expo++) {
        // your code goes here
        System.out.print(expo + " ");
    }
    System.out.println("");
}

输出:

2.0 --> 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 11.0 12.0 13.0 14.0 15.0 16.0 17.0 18.0 19.0 20.0 
3.0 --> 
4.0 --> 
5.0 --> 
6.0 --> 
7.0 --> 
8.0 --> 
9.0 --> 
10.0 --> 
11.0 --> 
12.0 --> 
13.0 --> 
14.0 --> 
15.0 --> 
16.0 --> 
17.0 --> 
18.0 --> 
19.0 --> 
20.0 --> 

要解决您的问题,您可以按照以下步骤更新代码。

for (root = 2; root <= 20; root++) {
    for (expo = 2; expo <= 20; expo++) {
        prodX = Math.pow(root, expo); //raises root to expo
        prodY = Math.pow(expo, root);// raises expo to root
        leySum1 = prodX + prodY;
        leySum2 += leySum1;
        System.out.println(leySum1);
    }
}

请参阅代码的Live Demo

答案 1 :(得分:1)

您需要为每次外循环运行重新初始化expo变量。

这个

double root, expo, prodX, prodY, leySum1 = 0, leySum2 = 0;
        for (root=2; root <= 20; root++) {
            for (expo=2; expo <= 20; expo++) {
                prodX = Math.pow(root, expo); //raises root to expo
                prodY = Math.pow(expo, root);// raises expo to root
                leySum1 = prodX + prodY;
                leySum2 += leySum1;
                System.out.println(leySum1);
            }
        }
        System.out.println("The sum of the leyland numbers " 
                + "up to 20 is " + leySum2);