我正在尝试创建一个程序,该程序接受来自用户的2个正整数,并将输出所输入的两个数字的最大公约数。这就是我所拥有的:
package assignment1solutions;
import stdlib.StdIn;
import stdlib.StdOut;
public class FindGCD {
public static long euclid(int a, int b) {
if (b == 0) {
return a;
}
return euclid(b, a%b);
}
public static void main(String[] args) {
StdOut.print("Enter a positive integer: ");
int a = Integer.parseInt(StdIn.readLine());
StdOut.print("Enter another positive integer: ");
int b = Integer.parseInt(StdIn.readLine());
StdOut.printf("The greatest common divisor is: %,d.", b,a%b);
}
}
答案 0 :(得分:2)
您甚至没有调用euclid
功能。您必须在写入输出之前调用该函数。
答案 1 :(得分:1)
我能够使用您的代码进行一些微小的更改......
public static long euclid(int a, int b) {
if (b == 0) {
return a;
}
return euclid(b, a%b);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int a = Integer.parseInt(scanner.nextLine().trim());
System.out.print("Enter another positive integer: ");
int b = Integer.parseInt(scanner.nextLine().trim());
// Call euclid, and Fix the format string.
System.out.printf("The greatest common divisor is: %d.", euclid(a,b));
}
我测试的是这样的
Enter a positive integer: 120
Enter another positive integer: 50
The greatest common divisor is: 10.
答案 2 :(得分:1)
您没有调用euclid
方法。此外,您始终只打印b
值。
变化:
StdOut.printf("The greatest common divisor is: %,d.", b,a%b);
为:
StdOut.printf("The greatest common divisor is: %,d.", euclid(a, b));
// or
System.out.printf("The greatest common divisor is: %,d.", euclid(a, b));