java中输出派的近似值_编写程序:计算π的近似值,π的计算
公式为
地榆炭的功效与作用展开全部
#include
春天的快乐main()
{ int n,i; double t,
sum;/*1*/
printf("请输⼊n的值\n");
scanf("%d",&n);
sum=2; i=1; t=2;/*2*/
while(i
/
*3*/ // sum=sum*t; i=i+1; }
printf("π的值=%f\n",t);/*4*/ }
或。
写⼀个Java程序来实现蒙特卡32313133353236313431303231363533e58685e5aeb931333431373336洛法求π的近似值:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class MonteCarloPi {
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("How many darts shoud I toss at the board?\n");
String s = br.readLine();
int numberOfDarts = Integer.im());
double radius = 1.0;
Dartboard d = new Dartboard(radius);
for(int i=1; i<=numberOfDarts; i++){
除夕的时间
Toss t = Random(radius);
d.strike(t);
}
double fractionIn = d.getFractionIn();
double pi = 4.0 * fractionIn;
System.out.println("Pi is approximately "+pi);
}
清炖豆腐
}
class Dartboard{
private double radius;
private int insideCircle, outsideCircle;
public Dartboard(double radius){
this.radius = radius;
insideCircle = 0;
outsideCircle = 0;
}
public void strike(Toss toss){
double x = X();
double y = Y();
if(Math.sqrt(x*x + y*y) < radius)
insideCircle++;
el
outsideCircle++;
}
public double getFractionIn() {
double total = (double) (insideCircle + outsideCircle); return (double) insideCircle/total;
}
}
class Toss{
private double x,y;
传统文化的作文public Toss(double x, double y){
aidedthis.x = x;
this.y = y;
}
public double getX(){return x;}
public double getY(){return y;}
public static Toss getRandom(double radius){
double x,y;
double size = Math.random();
double sign = Math.random();
size = size * radius;
if(sign > 0.5)
x = size;
el
x = -size;
size = Math.random();
sign = Math.random();
size = size * radius;
if(sign > 0.5)
y = size;
el
y = -size;
丽贵妃传return new Toss(x,y);
}
}
扩展资料:
C语⾔:⽤循环结构分别编写程序#include
void main()
{
\x09int n=1;
\x09float temp;
\x09float sum=0;
\x09do
\x09{
\x09\x09temp=(float)1/(2*n-1); \x09\x09if(n%2==1)
\x09\x09\x09sum+=temp;
纽崔莱倍立健片\x09\x09el
\x09\x09\x09sum-=temp;
\x09\x09n++;
\x09}while(temp>=0.000001); \x09printf("Pi=%f\n",sum*4);
}