V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
shayuvpn0001
V2EX  ›  程序员

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

  •  
  •   shayuvpn0001 · 2018-08-06 12:25:58 +08:00 · 1366 次点击
    这是一个创建于 2061 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    3 条回复    2018-08-06 13:32:13 +08:00
    xmh51
        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); 总是在最前面,即使实际执行可能在中间。
    zjp
        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
    shayuvpn0001
        3
    shayuvpn0001  
    OP
       2018-08-06 13:32:13 +08:00
    @xmh51
    @zjp

    =_=!!

    确实是我自己挖的坑,for 循环里开始不是用的 stringbuilder,是直接 printlin 出来的,这样确实没毛病,引入 sb 之后,在最后将结果一次性打印输出。实际 hit 是在第二次也就是 15 和 48 的时候发生的。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1395 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 23:41 · PVG 07:41 · LAX 16:41 · JFK 19:41
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.