编写程序,输入n的值,求 1/1-1/2+1/3-1/4+...+(-1)n-1
时间: 2023-12-05 13:03:10 浏览: 300
以下是两种实现方法:
方法一:Python实现
```python
n = int(input("请输入n的值:"))
sum = 0
for i in range(1, n+1):
sum += (-1)**(i-1) / i
print("sum = {:.4f}".format(sum))
```
方法二:C语言实现
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
int i = 1, n, d = 1;
double sum = 0;
scanf("%d", &n);
while (i <= n) {
sum += (1.0 / i) * d;
i++;
d *= -1;
}
printf("sum=%.4f\n", sum);
return 0;
}
```
阅读全文