题目描述:
求1-1/3+1/5-1/7+1/9…的值。
解题思路:
a,求出前50项和值。 b,求出最后一项绝对值小于1e-5的和值。
代码:
public class Main { public static void main(String[] args) { int a=0,b=0; int flag=1; int temp=0; int x=1; for(int i=1;i<=50;i++){ temp=1/x; a+=flag*temp; flag=-flag; x+=2; } flag=-1; temp=0; x=1; for(int i=1;i<=100;i++){ temp=1/x; b+=flag*temp; flag=-flag; x+=2; if(Math.abs(temp)<1e-5){ break; } } System.out.println("a="+a+" b="+b); } }