楼主要多少位呢?java.lang.PI 足够了吗?双精度的值.只要将输出格式化一下就可以了.PI的数值算法为:
{
double local,pi=0.0,w;
long i;
w=1.0/N //N为等分间隔
for(i=0;i<N;i++)
{
local= (i+0.5)*w;
pi=pi+4.0/(1.0+local*local);
}System.out.println("pi is"+pi*w);
}
{
double local,pi=0.0,w;
long i;
w=1.0/N //N为等分间隔
for(i=0;i<N;i++)
{
local= (i+0.5)*w;
pi=pi+4.0/(1.0+local*local);
}System.out.println("pi is"+pi*w);
}
int len=s.substring(s.indexOf('.')+1).length();
char[] c=new char[len];
Arrays.fill(c,'#');
String f="#."+new String(c);
DecimalFormat df=new DecimalFormat(f);
System.out.println(df.format(Math.PI));
{
int i;
Test(int i)
{
this.i=i;
String s=String.valueOf(Math.PI);
System.out.println(s.substring(0,i+2));
}
public static void main(String[] args)
{
new Test(5);
}
}
楼主结贴啦,这个简单明了
^_^,容易啊,用个charAt()就解决了
在四舍五入的时候,怎么把一个数的最后一位加一啊比如:3.141-->3.142具体怎么实现啊
先判断第i+1位的数值大小
然后再修改第i位或者取前i-1位,修改第i位之后再接上
public String getPI(int n){
String str = null;
String pattern = "#########################";
DecimalFormat df = new DecimalFormat("0." + pattern.substring(0,n-1));
double pi = Math.PI;
str = df.format(pi);
return str;
} public static void main(String[] args) {
PI pi = new PI();
System.out.println(Math.PI);
System.out.println(pi.getPI(5));
}
}
* Created on 2004-11-26
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;/**
* @author Hanbing
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class PI {
public String getPI(int n){
String str = null;
String pattern = "###############################################";
DecimalFormat df = new DecimalFormat("0." + pattern.substring(0,n));
double pi = Math.PI;
str = df.format(pi);
return str;
} public static void main(String[] args) {
System.out.println("Please enter a number:");
int n = 0;
try {
String strN=new BufferedReader(new InputStreamReader(System.in)).readLine();
n = Integer.parseInt(strN);
} catch (Exception e) {
System.out.print("您输入的位数不正确!");
System.exit(0);
}
PI pi = new PI();
System.out.println("默认的PI:" + Math.PI);
System.out.println("精确" + n + "位:" + pi.getPI(n));
}
}
===============
Please enter a number:
10
默认的PI:3.141592653589793
精确10位:3.1415926536