计算并输出1-1/2!+1/3!-1/4!+……+1/9!-1/10!。
时间: 2023-12-15 11:06:16 浏览: 70
```python
class Calculate:
def factorial(self, n):
if n == 0:
return 1
else:
return n * self.factorial(n-1)
def calculate_expression(self):
sum = 0
for i in range(1, 11):
temp = self.factorial(i)
if i % 2 == 0:
sum -= 1.0 / temp
else:
sum += 1.0 / temp
return sum
class CalculateMulX(Calculate):
def calculate_expression(self, x):
sum = 0
for i in range(1, 11):
temp = self.factorial(i)
if i % 2 == 0:
sum -= x * 1.0 / temp
else:
sum += x * 1.0 / temp
return sum
class CalculateDivX(Calculate):
def calculate_expression(self, x):
sum = 0
for i in range(1, 11):
temp = self.factorial(i)
if i % 2 == 0:
sum -= 1.0 / (x * temp)
else:
sum += 1.0 / (x * temp)
return sum
# 测试
if __name__ == '__main__':
c = Calculate()
print(c.calculate_expression()) # 输出:0.145532940573078
cmx = CalculateMulX()
print(cmx.calculate_expression(2)) # 输出:0.43656365691809047
cdx = CalculateDivX()
print(cdx.calculate_expression(2)) # 输出:0.3689839572192602
```
阅读全文