关于 Java 的 util 中随机数的问题

2018-08-06 12:25:58 +08:00
 shayuvpn0001

最近看 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 是新的随机值.但是执行结果却不是这样的,请问一下问题出在哪里?

1381 次点击
所在节点    程序员
3 条回复
xmh51
2018-08-06 12:46:09 +08:00
System.out.println("hit - " + p + ", " + q); System.out.println(sb); 打印顺序有问题 代码没问题。你这样的话 System.out.println("hit - " + p + ", " + q); 总是在最前面,即使实际执行可能在中间。
zjp
2018-08-06 13:03:44 +08:00
被你带沟里去了,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
shayuvpn0001
2018-08-06 13:32:13 +08:00
@xmh51
@zjp

=_=!!

确实是我自己挖的坑,for 循环里开始不是用的 stringbuilder,是直接 printlin 出来的,这样确实没毛病,引入 sb 之后,在最后将结果一次性打印输出。实际 hit 是在第二次也就是 15 和 48 的时候发生的。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/477234

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX