用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 + "%");
}
}