帮忙编一个Java程序,计算1-1⼀3+1⼀5-1⼀7+1⼀9-1⼀11…的前10000项之和

各位帮帮忙吧。谢谢啦
2024-12-21 12:40:40
推荐回答(3个)
回答1:

public class Test {
public static void main(String[] aergs) {
int n = 3;
double sum = 1;
for(int i = 0; i < 10000; i++, n+=2) {
if(i % 2 == 0) {
sum -= 1/n;
} else {
sum += 1/n;
}
}
System.out.println(sum);
}
}

回答2:

public class testAdd
{

public static void main(String[] args)
{
// TODO Auto-generated method stub

double sum = 0;

for (int i = 1,j=1; i <= 10000; i++, j+=2)
sum += (i& 1)==0 ? (double)1/j : -(double)1/j;

System.out.println("sum is:" + sum);
}
}

回答3:

public class Expression {
public static void main(String[] args) {
double sum = 0;
int j =1;
for(int i = 0; i < 10000; i++) {
sum+=j/(i*2+1);
j*=-1;
}
}
System.out.println(sum);
}
}