3.4 jmu-java-随机数-使用蒙特卡罗法计算圆周率的值 ,10 分
import java.util.Scanner;
import java.util.Random;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long seed=sc.nextLong();
int n=sc.nextInt();
Random random= new Random(seed);
double x,y=0;
long k=0,i=0;
for(i=0;i<n;i++){
int s;
if (i<1/n) {s=1;}
else {s=-1;}
x= random.nextDouble()*s; //产生随机数
y= random.nextDouble()*s;
if(x*x+y*y<1) k++;
}
double pi=4*(double)k/(double)i;
System.out.println(pi);
sc.close();
}
}
以上代码可以在eclipse中运行却在PTA上显示错误。因为我不了解如何产生-1到1之间的随机数。- 上一篇 »JAVA函数的返回值类型详解以及生成随机数的例题
- 下一篇 »[PHP]生成随机数,建立字典