Test2.java 题目:编写一个函数,输入n为偶数时,调用函数求1/2+1/4+...+1/n,当输入n为奇数时,调用函数1/1+1/3+...+1/n(利用指针函数)
时间: 2024-04-27 21:15:31 浏览: 106
Python中特殊函数集锦
```java
public class Test2 {
public static void main(String[] args) {
int n = 6;
double sum = 0;
if (n % 2 == 0) {
sum = evenSum(n);
} else {
sum = oddSum(n);
}
System.out.println(sum);
}
public static double evenSum(int n) {
double sum = 0;
for (int i = 2; i <= n; i += 2) {
sum += 1.0 / i;
}
return sum;
}
public static double oddSum(int n) {
double sum = 0;
for (int i = 1; i <= n; i += 2) {
sum += 1.0 / i;
}
return sum;
}
}
```
--相关问题--:
1. Java中什么是指针函数?
2. 如何判断一个数是
阅读全文