Java i中的死代码警告--

Java i中的死代码警告--,java,Java,我将尝试定义返回最大公约数的函数。 现在我遇到了一些障碍。 为什么死代码警告出现在i--? 我什么也感觉不到,所以请告诉我怎么了 public class Main { public static int function(int a, int b, int c) { int min; if (a > b) { if (b > c) { min = c; } el

我将尝试定义返回最大公约数的函数。 现在我遇到了一些障碍。 为什么死代码警告出现在i--? 我什么也感觉不到,所以请告诉我怎么了

public class Main {

    public static int function(int a, int b, int c) {
        int min;
        if (a > b) {
            if (b > c) {
                min = c;
            } else {
                min = b;
            }
        } else {
            if (a > c) {
                min = c;
            } else {
                min = a;
            }
        }
        for (int i = min; i > 0; i--) {
            if (a % i == 0 && b % i == 0 && c % i == 0) {
                return i;
            }
            return -1;
        }
        return 0;
    }

    public static void main(String[] args) {

        System.out.println("(400, 300, 750)의 최대 공약수 : " + function(400, 300, 750));

    }

}

for循环有一个if块,如果找到,则返回最大公约数。如果不是,则返回-1。所以循环永远不会继续,“我--”也永远不会被执行。这就是为什么它是一个死代码。移除“返回-1”,它应能正常工作

单步执行调试器中的代码通常是找到这些bug的最快方法。但是,只需检查作为
min
值的一个因子的值,就可以使代码运行得更快。这大大减少了迭代次数

public class Main {

    public static int function(int a, int b, int c) {
        int min;
        if (a > b) {
            if (b > c) {
                min = c;
            } else {
                min = b;
            }
        } else {
            if (a > c) {
                min = c;
            } else {
                min = a;
            }
        }
        for (int i = min; i > 0; i--) {
            if (a % i == 0 && b % i == 0 && c % i == 0) {
                System.err.println("Iterations " + (min + 1 - i));
                return i;
            }
        }
        return 0;
    }

    public static long gcd(long a, long b, long c) {
        long min = Math.min(a, Math.min(b, c));
        for (int j = 1, max = (int) Math.sqrt(min); j <= max; j++) {
            long i = min / j;
            if (a % i == 0 && b % i == 0 && c % i == 0) {
                System.err.println("Iterations: " + j);
                return i;
            }
        }
        return 1;
    }

    public static void main(String[] args) {
        System.out.println("(400, 300, 750)의 최대 공약수 : " + function(400, 300, 750));
        System.out.println("(400, 300, 750)의 최대 공약수 : " + gcd(400, 300, 750));
    }
}

在你的方法中,它必须考虑所有因素,从300到50(251个值)。但仅考虑300的因素,即300/1、300/2、300/3、300/4、300/5、300/6(6个值),速度要快得多。

使用您发布的代码,我没有收到任何警告或错误。我得到以下输出(400、300、750)의 최대 공약수 : -是的,我也这样做了。但是我想得到'50',最大公约数为400300750,去掉
返回-1
,循环只执行一次,所以它不是循环。我非常尊重你的建议。这对我很有帮助!!!!谢谢
(400, 300, 750)의 최대 공약수 : 50
(400, 300, 750)의 최대 공약수 : 50
Iterations 251
Iterations: 6