import java.util.Random;
import java.util.Scanner;
public class Demo {
public static void function(float a, float b, int loop) {
/**
* 用于统计落入指定区域点的次数
*/
int count = 0;
/**
* 随机点的横坐标
*/
float x;
/**
* 随机点的纵坐标
*/
float y;
/**
*
* @param a
* 矩形的长
* @param b
* 矩形的宽
* @param loop
* 循环次数
*/
for (int i = 1; i <= loop; i++) {
Random random = new Random();
// 产生 -2/a 至 2/a之间的数字
x = random.nextFloat() * a - a / 2;
// 产生 -2/b 至 2/b之间的数字
y = random.nextFloat() * b - b / 2;
// System.out.println(x+" "+y);
if ((x > (-a / 2) && x < 0 && y > (-b / 2) && y < 0)
|| (x > 0 && x < (a / 2) && y > 0 && y < (b / 2) - b * x
/ a)) {
count++;
}
}
System. out.println("射到目标区域的次数为: " + count);
double result = count * 100 / loop;
System. out.println("模拟概率为: " + result + "%");
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System. out.println("请输入矩形的宽:" );
float width = scan.nextFloat();
System. out.println("请输入矩形的高:" );
float height = scan.nextFloat();
System. out.println("请输入模拟次数:" );
int loop = scan.nextInt();
function(width, height, loop);
}
}
运行结果: