3

大家好,我是Java的初学者,我的英语不好,希望你能理解我的问题:

public static void main(String[] args) {

    int i, a, b, c, d, yil = 1999, rt = 0;


    do{
            //loop searching for 1976
            for( i = 1900; i < 2000; i++){
            //separate "i" to the digits
            a = i / 1000;
            b = i % 1000 / 100;
            c = i % 1000 % 100 / 10;
            d = i % 1000 % 100 % 10;
            rt = a + b + c + d;
            }}
            //while rt=23 and i=1976 equation will be correct then exit the loop and print the 1976.
            while( rt == yil - i );
        System.out.println("Yıl = " + i );

}

但是当我运行程序时,它总是显示 2000 而不是 1976。

4

1 回答 1

3

您混乱的增量可能会隐藏它,但您无法摆脱for循环。它总是走到最后,那就是i=2000

for( i = 1900; i < 2000; i++){
   ... // no break in there
}
...
System.out.println("Yıl = " + i );

在您的情况下没有理由有两个循环。看来你想要的是

        int i, a, b, c, d, yil = 1999, rt = 0;
        //loop searching for 1976
        for( i = 1900; i < 2000; i++){
            //separate "i" to the digits
            a = i / 1000;
            b = i % 1000 / 100;
            c = i % 1000 % 100 / 10;
            d = i % 1000 % 100 % 10;
            rt = a + b + c + d;
            if (rt==yil-i) break;
        }
        System.out.println("Yıl = " + i );  }

这输出

Yıl = 1976
于 2012-10-21T15:20:20.340 回答