编写一个用户自定义函数fun(n),功能是计算1+1/2+1/3+…1/n的和并返回,键盘输入一个数,调用函数fun(),计算并保留两位小数输出
时间: 2024-02-07 19:02:03 浏览: 25
```
def fun(n):
sum = 0
for i in range(1, n+1):
sum += 1/i
return round(sum, 2)
n = int(input("请输入一个正整数:"))
result = fun(n)
print("1到{}的倒数之和为:{}".format(n, result))
```
相关问题
C语言编写自定义函数通过键盘输入一个正整数n,计算 sum = 1 + 1/(1+2) + 1/(1+2+3) +...+1/(1+2+3+..+n),
以下是C语言编写自定义函数通过键盘输入一个正整数n,计算sum = 1 + 1/(1+2) + 1/(1+2+3) +...+1/(1+2+3+..+n)的代码:
```c
#include <stdio.h>
double fun(int n);
int main()
{
int n;
double sum = 0;
printf("请输入一个正整数n:");
scanf("%d", &n);
for (int i = 1; i <= n; i++)
{
sum += fun(i);
}
printf("sum = %lf", sum);
return 0;
}
double fun(int n)
{
double res = 0;
for (int i = 1; i <= n; i++)
{
res += i;
}
return 1 / res;
}
```
用递归的方法编写自定义函数,求:s=1+1/(1+2)+1/(1+2+3)+...+1/(1+2+3+...+10) 。c语言
以下是用递归的方法编写自定义函数,求s=1+1/(1+2)+1/(1+2+3)+...+1/(1+2+3+...+10)的C语言代码:
```c
#include <stdio.h>
double fun(int n) {
if (n == 1) {
return 1;
} else {
double sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
return 1 / sum + fun(n - 1);
}
}
int main() {
double s = fun(10);
printf("s = %lf", s);
return 0;
}
```
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.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)