编程计算, sn=(1-1/2)+(1/3-1/4)+...+(1/(2n-1)-1/(2n)),结果保留两位小数。 输入格式: 输入整数n值。 输出格式: 输出sn值。
时间: 2023-10-21 16:07:11 浏览: 44
以下是Python 3代码实现:
```python
n = int(input())
s = 0
for i in range(1, n+1):
s += 1/(2*i-1) - 1/(2*i)
print('%.2f' % s)
```
输入n值后,我们定义一个变量s表示结果。然后通过for循环从1到n迭代,每次加上1/(2i-1) - 1/(2i)的值。最后用字符串格式化输出结果,保留两位小数。
相关问题
c语言编程求s=1-1/3+1/5-1/7+...1/101中s的值
根据提供的引用内容,以下是一个C语言编程求s=1-1/3+1/5-1/7+...1/101中s的值的例子:
```c
#include <stdio.h>
void fun(float *sn, int n);
int main() {
float s;
int n = 50; // n的值为50,表示计算到1/101
fun(&s, n);
printf("s = %f\n", s); // 输出:s = 0.784398
return 0;
}
void fun(float *sn, int n) {
float s = 1.0, w, f = -1.0;
int i;
for (i = 1; i <= n; i++) {
f = -f;
w = f / (2 * i + 1);
s += w;
}
*sn = s;
}
```
编程求s=1-1/3+1/5- 1/7+...1/101 中s的值
根据提供的引用内容,以下是一个计算s的值的C代码示例:
```c
#include <stdio.h>
void fun(float* sn, int n) {
float s = 0.0, w, f = -1.0;
int i = 0;
for (i = 0; i <= n; i++) {
f = -1 * f;
w = f / (2 * i + 1); s += w;
}
*sn = s;
}
int main() {
int n = 50;
float b = 0;
float* PP = &b;
fun(PP, n);
printf("%f\n", *PP);
return 0;
}
```
运行上述代码,将会输出s的值为0.784398。这是根据公式S=1-1/3+1/5-1/7+…+1/(2n+1)计算得出的结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)