我正在编写一个程序,该程序使用 GCD(a, b) = GCD(b, r) r = a%b 的欧几里得算法。我写了一个方法,该方法应该返回一个整数供 main 方法吐出,但是当我要求它这样做时,它说它没有返回一个整数。这是代码
public class Euclid {
public static int GCD(int a, int b)
{
while (b != 0)
{
int r = a%b;
System.out.println("(" +a+ "," +b+ ")");
b = r;
a = b;
if(b == 0)
{
return a;
}
}
}
public static void main(String[] args)
{
System.out.println(GCD(36, 20));
}
}
最佳答案
在代码中,如果 b == 0
,它不会返回 int
或与此相关的任何值。您必须处理这种情况,很可能是通过指定默认返回值。
public static int GCD(int a, int b)
{
while (b != 0)
{
int r = a%b;
System.out.println("(" +a+ "," +b+ ")");
b = r;
a = b;
if(b == 0)
{
return a;
}
}
return 0;
}
关于java - 方法必须返回 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15191611/