2个回答
展开全部
public class Test {
public static void main(String[] args) {
int num = 10;
int sign = 1;
float sum = 0f;
int x = 1;
for (int i = 0; i < num; i++) {
sum = sum + sign * (1.0f / x);
x = x + 2;
sign = sign * (-1);
}
System.out.println(sum);
System.out.println(1 - 1.0 / 3 + 1.0 / 5 - 1.0 / 7 + 1.0 / 9 - 1.0 / 11
+ 1.0 / 13 - 1.0 / 15 + 1.0 / 17 - 1.0 / 19);
}
}
结果:
0.7604599
0.7604599047323508
public static void main(String[] args) {
int num = 10;
int sign = 1;
float sum = 0f;
int x = 1;
for (int i = 0; i < num; i++) {
sum = sum + sign * (1.0f / x);
x = x + 2;
sign = sign * (-1);
}
System.out.println(sum);
System.out.println(1 - 1.0 / 3 + 1.0 / 5 - 1.0 / 7 + 1.0 / 9 - 1.0 / 11
+ 1.0 / 13 - 1.0 / 15 + 1.0 / 17 - 1.0 / 19);
}
}
结果:
0.7604599
0.7604599047323508
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询