(1) 编写一个函数,输入n为偶数时,调用函数求1/2+1/4+...+1/n,当输入n为奇数时,调用函数1/1+1/3+...+1/n。
时间: 2023-11-24 20:08:40 浏览: 64
c代码-请编写函数sum,其功能是:用for循环语句求1到n之间所有偶数之和(若n为偶数包括n), 并将结果返回给主函数。(n值由主函数传入)
以下是C语言实现的代码:
```c
#include <stdio.h>
double oushu(int n) {
double sum = 0;
for (double i = 2; i <= n; i += 2) {
sum = sum + 1 / i;
}
return sum;
}
double jishu(int n) {
double sum = 0;
for (double i = 1; i <= n; i += 2) {
sum = sum + 1 / i;
}
return sum;
}
int main() {
int n;
double a;
printf("请输入一个数:");
scanf("%d", &n);
if (n % 2 == 0) {
a = oushu(n);
printf("和为%f", a);
} else {
a = jishu(n);
printf("和为%f", a);
}
return 0;
}
```
以下是Python实现的代码:
```python
def oushu(n):
sum = 0
for i in range(2, n+1, 2):
sum = sum + 1 / i
return sum
def jishu(n):
sum = 0
for i in range(1, n+1, 2):
sum = sum + 1 / i
return sum
n = int(input("请输入一个数:"))
if n % 2 == 0:
a = oushu(n)
print("和为", a)
else:
a = jishu(n)
print("和为", a)
```
阅读全文