用Java编程计算: 一根木棍折三段,能构成三角形的概率

用Java编程计算: 一根木棒折三段,能构成三角形的概率

面试时遇到的一道恶心的笔试题目:一根木棒折为三段,这三段可以构成一个三角形的概率?


public class Triangle {
    /**
     * 一根绳子任意切两刀组成三角形的概率
     *
     * @param args
     */
    private static long x = -1L; // first side of the triangle
    private static long y = -1L; // second side of the triangle
    private static long z = -1L; // thirdly side of the triangle
    private static long length = 1000L; // length of the triangle
    private static long loop = 10000000L; // how many time to run?
    private static long num = 0; // how many valid triangles?

    public static void main(String[] args) {
        method();

    }

    private static void method() {
        for (long i = 0L; i < loop; i++) {
            // to keep valid time for loop
            while (true) {
                x = (long) (Math.random() * length);
                y = (long) (Math.random() * length);
                z = length - x - y;
                if (z > 0L && x > 0L && y > 0L) {
                    break;
                }
            }
//            System.out.println(x + " " + y + " " + z);
            if (x + y > z && x + z > y && z + y > x) {
//                System.out.println(x + " " + y + " " + z);
                num++;
            }
        }
        double percent = ((num * 1.0) / loop) * 100; // "long" convert to "double"
        System.out.println(percent + "%");

    }

}