int n){ int i = 1; int commyue = 0; int c = m; if (c < n) c = n; while (i
求JAVA代码
你好:
楼上已经贴出了代码,我在此只回答第3小问
static关键字表示的是静态方法,此处在main方法中可以直接调用gcd方法.
按照楼上的代码,如果去掉static,需要先初始化一下ComputeGCD类 再去用类的实例去调用方法。如下:
public class ComputeGCD {public int gcd(int m,int n){ int r = m % n; while (r!=0) { m = n; n = r; r = m % n; } return n; } public static void main(String[] args){ ComputeGCD c = new ComputeGCD(); System.out.println("gcd(24,16)="+c.gcd(24,16)); System.out.println("gcd(255,25)="+c.gcd(255,25)); }}2013-11-15
程序如下:
public class ComputeGCD { public static void main(String[] args) { int t = gcd(24,16); System.out.println("gcd(24,16) = " +t); int t1 = gcd(225,25); System.out.println("gcd(225,25)"+t1); } public static int gcd(int m,int n){ int i = 1; int commyue = 0; int c = m; if (c < n) c = n; while (i <= c) { if (m % i == 0 && n % i == 0) commyue = i; i++; } return commyue; }}
2 .运行结果
gcd(24,16) = 8gcd(225,25) = 25
3.去掉保留字static报:Cannot make a static reference to the non-static method gcd(int, int) from the type ComputeGCD
2013-11-15
public class ComputeGCD{ public static int gcd(int m,int n) { int r=m%n; while (r!=0) { m=n; n=r; r=m%n; } return n; } public static void main(String[] args) { System.out.println("gcd(24,16)="+gcd(24,16)); System.out.println("gcd(255,25)="+gcd(255,25)); /*输出结果 gcd(24,16)=8 gcd(255,25)=5 */ }}2013-11-15