程序填空题 5 函数题 3 编程题 3 1-1 调用函数fun计算表达式1+1/2+1/3+···+1/n的值并输出 分数 15 作者 崔孝凤 单位 山东理工大学 下列程序的功能是调用函数fun计算表达式1+1/2+1/3+···+1/n的值并输出,结果保留3位小数,不添加任何提示信息,请填空完成程序功能。 #include <stdio.h> double fun(int n) {double t=1.0; int i; for(i=2; i<=n ;i++) t=; return t ; } int main(void) {int m; double s; scanf("%d",&m); s= ; //调用函数 printf() ; return 0; }
时间: 2024-04-04 11:29:45 浏览: 30
#include <stdio.h>
double fun(int n) {
double t = 1.0;
int i;
for(i = 2; i <= n; i++) {
t += 1.0 / i; // 表达式1+1/2+1/3+...+1/n 的计算公式
}
return t;
}
int main(void) {
int m;
double s;
scanf("%d", &m);
s = fun(m); // 调用函数
printf("%.3lf", s); // 输出结果并保留3位小数
return 0;
}
相关问题
填空完成以下计算 s=1+1/2+1/3+……+1/10 的程序
以下是计算 s=1+1/2+1/3+……+1/10 的程序:
```c
#include <stdio.h>
int main() {
double s = 0.0; // 初始化 s 为 0.0
int i;
for (i = 1; i <= 10; i++) {
s += 1.0 / i; // 累加每一项
}
printf("s = %lf\n", s); // 输出结果
return 0;
}
```
在这个程序中,我们使用了一个 double 类型的变量 s 来存储最终的和,使用了一个 for 循环来遍历每一项并将其累加到 s 中。需要注意的是,这里将 1.0 作为除数,是为了保证除法的精度,从而得到正确的结果。最后,我们使用 printf 函数输出结果。
下列程序的功能是调用函数fun计算表达式1+1/2+1/3+···+1/n的值并输出,结果保留3位小数,不添加任何提示信息,请填空完成程序功能。
```python
def fun(n):
sum =
for i in range(1, n+1):
sum += 1/i
return sum
n = int(input())
result = fun(n)
print("{:.3f}".format(result))
```
程序的功能是调用函数fun计算表达式1+1/2+1/3+···+1/n的值并输出,结果保留3位小数。程序中使用了一个函数fun,该函数接受一个参数n,计算表达式的值并返回结果。主程序中读入n的值,调用函数fun计算结果,并使用格式化字符串输出结果。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://img-home.csdnimg.cn/images/20210720083646.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)