最近看 java 的时候,碰到了一个问题,代码如下:
package com.company;
import java.util.Random;
public class Main {
final static int MAX = 100;
final static int MIN = 10;
public static int gcd(int p, int q) {
return (q == 0) ? p : gcd(q, p % q);
}
public static void main(String[] args) {
// write your code here
int p, q;
Random r = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; i++) {
p = r.nextInt(MAX) % (MAX - MIN + 1) + MIN;
q = r.nextInt(MAX) % (MAX - MIN + 1) + MIN;
while (p == q) {
System.out.println("hit - " + p + ", " + q);
q = r.nextInt(MAX) % (MAX - MIN + 1) + MIN;
}
sb.append("GCD of " + p + " and " + q + " is " + gcd(p, q));
sb.append(System.getProperty("line.separator"));
}
System.out.println(sb);
return;
}
}
输出结果是:
hit - 15, 15
GCD of 31 and 30 is 1
GCD of 15 and 48 is 3
GCD of 78 and 44 is 2
GCD of 89 and 18 is 1
GCD of 60 and 17 is 1
GCD of 86 and 59 is 1
GCD of 73 and 18 is 1
GCD of 22 and 84 is 2
GCD of 75 and 66 is 3
GCD of 99 and 46 is 1
这里有一个问题,我本来的意思是,当 q 取到与 p 一样的随机值时,重取一次,直到与 p 不一致为止.在实际代码运行中,当 p 为 15 的时候,p 应该不重新取值,q 重新取值,第一次 hit 的时候,p 应该是保持 15,而 q 是新的随机值.但是执行结果却不是这样的,请问一下问题出在哪里?
1
xmh51 2018-08-06 12:46:09 +08:00 1
System.out.println("hit - " + p + ", " + q); System.out.println(sb); 打印顺序有问题 代码没问题。你这样的话 System.out.println("hit - " + p + ", " + q); 总是在最前面,即使实际执行可能在中间。
|
2
zjp 2018-08-06 13:03:44 +08:00 via Android 1
被你带沟里去了,debug 一会发现没问题啊…
因为你用 StringBuilder 保存了结果,在最后一次性输出,实际运行是: GCD of 31 and 30 is 1 hit - 15, 15 GCD of 15 and 48 is 3 GCD of 78 and 44 is 2 |
3
shayuvpn0001 OP |