编写一个函数:输入n为偶数时,调用函数求1/2+1/4+...+1/n;当输入n为奇数时,调用函数1/1+1/3+...+1/n。
public class Example38 {
public static void main(String[] args) {
double d = sum(3);
System.out.println("运算结果为:" + d);
}
public static double sum(int n) {
double sum = 0.0;
if (n % 2 == 0) {
for (int i = 2; i <= n; i += 2) {
sum += 1.0 / i;
}
} else {
for (int i = 1; i <= n; i += 2) {
sum += 1.0 / i;
}
}
return sum;
}
}
时间: 2024-10-09 22:43:28