62,612
社区成员
发帖
与我相关
我的任务
分享
import java.util.Random;
import java.util.Scanner;
public class Test {
static class Point{
private double x;
private double y;
public Point(double x,double y){
this.x=x;
this.y=y;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
public void setX(double x) {
this.x = x;
}
public void setY(double y) {
this.y = y;
}
public double getDistance(Point p){
return Math.sqrt((this.x-p.getX())*(this.x-p.getX())+(this.y-p.getY())*(this.y-p.getY()));
}
}
public static double getPI(long seed,int n){
int count=0;
Random random = new Random();
random.setSeed(seed);
for(int i=0;i<n;i++){
double x=random.nextDouble()*(1.0 +1.0) -1.0;
double y=random.nextDouble()*(1.0 +1.0) -1.0;
Point p = new Point(x,y);
if(p.getDistance(new Point(0,0))<=1){
count++;
}
}
double b = ((double)count)/n;
return (4*1*b)/1;
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("请输入随机种子:");
long seed = sc.nextLong();
System.out.println("请输入投入的点数:");
int n = sc.nextInt();
System.out.println("PI="+getPI(seed,n));
}
}
运行结果
请输入随机种子:
2
请输入投入的点数:
100000
PI=3.14684