两个求 π 的程序

 

---------------------------------------------

C++ Version

---------------------------------------------

 

#include <iostream>
#include <stdlib.h>

using namespace std;
//double func(double&)const;   Isn't needed;
class Pi
{
 public:
  friend double func(Pi&)throw(double);
  Pi(int n):interval(n){};
  double loop(double)const;
 private:
  int interval;
};
double Pi::loop(double x)const
{
 return 4/(1+x*x);
}
double func(Pi& p)throw(double)
{
 double h=1/static_cast<double>(p.interval);
 //cout<<h<<endl;
 static double presum,sum;
 for(int i=1;i<p.interval;i++)
 {
  double xi=i*h;
  presum+=p.loop(xi);
 }
  sum=h/2*(p.loop(0.0)+2*presum+p.loop(1.0));//if "double loop(double&)const;",cannot be used like this!
  //cout<<"sum="<<sum<<"/n";;
  if(sum<=3.14)
   throw sum;
  else
   return sum;

}

int main(int argc, char *argv[])
{
  Pi p(100);
  try
  {
  cout<<"pi="<<func(p)<<endl;
  }
  catch(double s)
  {
   cout<<"Error!"<<endl;
   cout<<"pi="<<s<<" is not accurate!"<<endl;
  }
 
  system("PAUSE"); 
  return 0;
}

 

----------------------------------------------

Java Version

-----------------------------------------------

package Exc;
import java.util.Scanner;

public class Pi
{

 public static void main(String[] args)
 {
 double b = 1;//int b=1,see h;
 double a = 0;
 double sum = 0;
 double p=0;
 Scanner sc = new Scanner(System.in);
 System.out.println("Input the number n of intervals.");
 int n = sc.nextInt();
 
 double h=(b-a)/n;
 System.out.println("h=" + h);
 for(int i=1;i < n;i++)
    {
 
  double xi=a + i*h;
 
   sum=sum+2*f(xi);
  
  
  }
  try
  {
   
      p=summary(sum,h,a,b);
    
  }
  catch (ErrorException e)
  {
   System.out.println("caught: " + e);
   System.out.println("message: " + e.getMessage());
   System.out.println("stack: " + e.getStackTrace());
   return ;
  }
  finally
  {
   System.out.println("pi=" + p);
  }


 }

 static double summary(double s,double h,double a,double b) throws ErrorException
 {

      s =h / 2 * (s + f(a) + f(b));
  if (s < 3.1415926)
   throw new ErrorException("pi = " + s +" is not accurate.");
  else
   return s;
 
 }
 static class ErrorException extends Exception
 {
  ErrorException( String  what) { super(what); }
 
 }

 static double f(double x)
 {
  return 4/(1+x*x);
 
 }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值