利用键盘输入n,输出 1-2/5+3/7-4/9+5/11- (共n项)的值,结果保留3位小数。
时间: 2023-12-12 19:19:00 浏览: 33
以下是Python实现:
n = int(input("请输入n: "))
start = 1
end = 2/5
for i in range(n):
if i == n-1:
print("{:.3f}".format(start))
else:
print("{:.3f}-{:.3f}".format(start, end), end=" ")
start = end + 2/(6+2*i)
end = start + 1/(6+2*i)
相关问题
C语言 利用键盘输入n,输出 1-2/5+3/7-4/9+5/11- (共n项)的值,结果保留3位小数。
```
#include <stdio.h>
int main()
{
int n;
scanf("%d", &n); // 输入n
double numerator = 1.0; // 分子
double denominator = 2.0; // 分母
double result; // 结果
for(int i=1; i<=n; i++){
result = numerator/denominator;
printf("%.3f ", result); // 输出结果,保留3位小数
numerator += 2.0; // 分子加2
denominator += 2.0; // 分母加2
if(i%2 == 0){ // 每两项之间的符号
printf("-");
numerator -= 2.0; // 分子减2,恢复原值
denominator += 2.0; // 分母加2
}
else{
printf("/");
}
}
return 0;
}
```
3.编写主程序调用子程序,求数列和。利用键盘输入n,输出 1-2/5+3/7-4/9+5/11- (共n项)的值,结果保留3位小数。
def sub_program(n):
sum = 0
for i in range(1, n+1):
if i % 2 == 1:
sum += i/(2*i+1)
else:
sum -= i/(2*i+1)
return round(sum, 3)
n = int(input("请输入n的值:"))
result = sub_program(n)
print("数列的和为:", result)
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](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)