什么会导致for循环在它应该递增时递减?

K M*_*Man 5 java loops for-loop increment decrement

我写了一个计算方法来计算父亲多久以前和他儿子一样多的年龄,以及从现在开始多少年这是真的.出乎意料的是,对于一个8岁的父亲和一个3岁的儿子来说,它回归"2 - 2年前".同样出人意料的是,对于一个3岁的父亲和一个2岁的儿子,它将在"1年后回归".我并不担心如何改进代码,因为我已经知道如何做到这一点.相反,我很困惑为什么for循环计数器在它应该递增时似乎递减.

这是我的代码.

public class TwiceAsOld {

    public static void twiceAsOld (int currentFathersAge, int currentSonsAge) {

        int yearsAgo;
        int yearsFromNow;
        int pastFathersAge = currentFathersAge;
        int pastSonsAge = currentSonsAge;
        int futureFathersAge = currentFathersAge;
        int futureSonsAge = currentSonsAge;

        for (yearsAgo = 0; pastFathersAge != 2 * pastSonsAge; yearsAgo++) {
            pastFathersAge--;
            pastSonsAge--;
        }

        System.out.println("The father was last twice as old as the son " + yearsAgo + " years ago.");

        for (yearsFromNow = 0; futureFathersAge != 2 * futureSonsAge; yearsFromNow++) {
            futureFathersAge++;
            futureSonsAge++;
        }

        System.out.println("The father will be twice as old as the son in " + yearsFromNow + " years from now.");

    }

    public static void main(String[] args) {
        twiceAsOld(8, 3);
        twiceAsOld(3, 2);
    }
}
Run Code Online (Sandbox Code Playgroud)

使用两次AsOld(8,3)时,for循环的增量似乎已经反转,从0开始倒计数而不是向上计数.有两次AsOld(3,2),-1可能代表一个错误,表明父亲从来没有像他儿子一样大两倍,也永远不会.我不明白的是什么会导致for循环开始递减i值,当它应该增加时.我期待计数器无限增加,直到程序内存不足.

我已经知道如何改进这个程序了,但我很好奇for循环中的计数器如何在它应该增加时减少.任何人都能解释一下吗?

(更新:感谢大家的答案.我不敢相信我忘记了整数溢出.我尝试使变量变长而不是整数,但这使程序更慢.无论如何,现在我意识到计数器一直在增加直到它飞越并以负值降落.)

mkj*_*kjh 4

它变成负值,因为这就是 Java 中 int 计算溢出时发生的情况。

看看 https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.18.2

它说

如果整数加法溢出,则结果是以某种足够大的二进制补码格式表示的数学和的低位。如果发生溢出,则结果的符号与两个操作数值的数学和的符号不同。