Java简易程式-求圆周率 & 投骰子概率
求圆周率:假设正方形标靶,中有内切圆。正方形边长L=2,内切圆半径r=1;
内切圆和正方形的面积比:πr²/L² = π/4 => 乘以4即为圆周率;
假设 x 与 y 坐标为随机标点,中心点-1--1范围内,即为内切圆面积.
public class Pi{
public static void main(String[] args){
int hit = 0;
int total = 0;
while(true){
float x = (float)Math.random()*2-1;
float y = (float)Math.random()*2-1;
if(x*x + y*y < 1){
hit++;
}
System.out.print((float)hit/(float)total*4.0F);
total++;
// 3.1415926
}
}
}
投方形骰子计算各面出现的概率
设定数组,循环次数,每次随机生成一个0-5的数字,对应数组下标;
public class Dice{
public static void main(String[] args) {
int[] dice = new int[6];
int NUM = 10000;
for (int i = 0; i < NUM; i++) {
int number = (int) (Math.random()*5.99999);
dice[number]++;
}
System.out.println("One:" + dice[0] +
" Two:" + dice[1] +
" Three:" + dice[2] +
" Four:" + dice[3] +
" Five:" + dice[4] +
" Six" + dice[5]);
}
}