编写一个JAVA应用程序,计算1-1⼀3+1⼀5-1⼀7+1⼀9-1⼀11+...前1OOO项的和!

2024-12-15 07:07:12
推荐回答(4个)
回答1:

public static void main(String[] args) {
float count = 0;//count为总和
for(float i = 0;i<1000;i++){
if(i%2 == 0){
count += (1/(1+2*i));//奇数个时进行相加
}else if(i%2 == 1){
count -= (1/(1+2*i));//偶数个时相减
}
}
System.out.println("他们的和为:"+count);
}

回答2:

public static void main(String[] args) {
double result = 0;
for(int i = 1, j = 1; i <= 1000; i++){
if(i % 2 == 0){
result = result - 1/(double)j;
}else{
result = result + 1/(double)j;
}
j = j + 2;
}
System.out.println(result);
}

回答3:

public static void main(String[] args) {
int n=1,k=1;
double value=1;
while(n<1000){
n=n+2;k++;
if(k%2==0){
value=value-(double)1/n;
}else{
value=value+(double)1/n;
}

}
System.out.println(value);
}

回答4:

for(int i=1;i<=1000;i++) {1+(-1)n次方*1/n+2}