Java语言求 y=1-1⼀2+1⼀3-1⼀4+……+1⼀99-1⼀100

2024-12-19 19:55:30
推荐回答(2个)
回答1:

public abstract class Test{
public static void main(String[] args) {
double result=1;
double a=1;//忘记要转换类型了,都必须是double类型!
int num=100;
for(int i=2;i<=num;i++){
if(i%2==0){//分母是偶数,减去1/i
result=result-(a/i);
}
else{//分母是奇数,加上1/i
result=result+(a/i);
}
}
System.out.println("最后结果是:"+result);
}
}

回答2:

import java.math.*;
public class ma1{
static double num1=0;
public static void main(String[] args) {
for (int i=1;i<=100;i++) {
num1=num1+Math.pow(-1,i+1)*(1/i);
}
System.out.println(num1);
}
}