编写一个函数fun,参数为n,返回s,s=1+1/2+1/3+•••1/n,从键盘输入a和b,回车分隔,调用该函数计算fun(a)
时间: 2023-06-11 15:04:22 浏览: 261
到fun(b)的和。以下是代码实现:
```python
def fun(n):
s = 0
for i in range(1, n+1):
s += 1/i
return s
a, b = input().split()
a = int(a)
b = int(b)
sum = 0
for i in range(a, b+1):
sum += fun(i)
print(sum)
```
请问这样的回答是否满意?
相关问题
计算公式s=1+1/(1+2)+1/(1+2+3)+…+1/(1+2+…+n)的值 编写函数fun(), 实现功能:根据公式s=1+1/(1+2)+1/(1+2+3)+…+1/(1+2+…+n)计算s,计算结果作为函数值返回,n通过形参传入。
计算公式s=1+1/(1+2)+1/(1+2+3)+…+1/(1+2+…+n)的值为s=1/(1)+1/(1+2)+1/(1+2+3)+…+1/(1+2+…+n),即s的每一项分母为1到n的和,分子为1,2,3,...,n。因此,可以使用循环来计算s的值。
```
// 代码类型:C语言
double fun(int n){
double s = 0;
int sum = 0;
for(int i = 1; i <= n; i++){
sum += i;
s += 1.0 / sum;
}
return s;
}
```
编写函数fun,计算下列多项式:s=1+x+x**2/2!+x**3/3!+•••+x**n/n!
Sure, I can help you with that! Here is the function:
```python
def fun(x, n):
s = 1
fact = 1
for i in range(1, n+1):
fact *= i
s += (x ** i) / fact
return s
```
Simply pass in the value of `x` and the number of terms `n` you want to use in the approximation. The function will return the value of the sum of the series.
Hope this helps!
阅读全文