Java入门 不懂就问
计算1+1/2+1/3+1/4+......+1/n这样一个数列
假如n=50000
为什么从右向左算要比从左向右算要精确?
运行代码如下
public class calculate1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
double sum1=0.0;
double sum2=0.0;
for(double i=1;i<=50000;i+=1)
{
sum1+=(double)(1/i);
}
for(double j=50000;j>=1;j-=1)
{
sum2+=(double)(1/j);
}
System.out.println("Calculate from left to right:"+sum1);
System.out.println("Calculate from right to left:"+sum2);
}
}
运行结果:
Calculate from left to right:11.397003949278504
Calculate from right to left:11.397003949278519