不废话,直接上代码,需要的可以直接拷走:
/**
* java代码实现:1-1/2+1/3-1/4+...+1/100
* @author hbxfyxw
* @blog http://blog.csdn.net/hbxfyxw
*/
public class Calc {
public static void main(String[] args) {
double a = 0, b = 0;
for (int i = 1; i <= 100; i++) {
if (i % 2 == 1) {
a = a + (double) 1 / i;
} else {
b = b + (double) 1 / i;
}
}
System.out.println(a - b);
}
}