把加减乘除函数都整合进去形成完整的64位减乘除计算器,并优化一下使结构更清晰,便于理解
时间: 2024-10-27 10:07:29 浏览: 13
为了创建一个完整的64位算术计算器,我们将把加、减、乘、除四个基本运算功能整合到一个模块中,保持代码结构清晰。这里是一个简化版的示例,使用Python来实现:
```python
class Calculator:
def __init__(self, max_value=2**64 - 1):
self.max_value = max_value
self.supported_operations = ['+', '-', '*', '/']
def validate_input(self, num1, num2, op):
try:
num1 = int(num1)
num2 = int(num2)
except ValueError:
return False
if not isinstance(op, str) or op not in self.supported_operations:
return False
return abs(num1) <= self.max_value and abs(num2) <= self.max_value
def add(self, num1, num2):
return num1 + num2
def subtract(self, num1, num2):
return num1 - num2
def multiply(self, num1, num2):
return num1 * num2 % (self.max_value + 1)
def divide(self, num1, num2):
if num2 == 0:
raise ValueError("除数不能为零")
quotient = num1 // num2
remainder = num1 % num2
return quotient, remainder
def calculate(self, expression):
tokens = expression.split()
if len(tokens) != 3:
return "语法错误"
operator, num1, num2 = tokens[0], tokens[1], tokens[2]
if not self.validate_input(num1, num2, operator):
return "输入错误"
if operator == '+':
result = self.add(int(num1), int(num2))
elif operator == '-':
result = self.subtract(int(num1), int(num2))
elif operator == '*':
result = self.multiply(int(num1), int(num2))
elif operator == '/':
quotient, remainder = self.divide(int(num1), int(num2))
result = f"商:{quotient}, 余数:{remainder}"
else:
return "不支持的操作"
return result
# 使用示例
calculator = Calculator()
expression = "50 * 7 / 3"
result = calculator.calculate(expression)
print(result)
```
这个`Calculator`类包含了所有必要的方法,包括验证输入、加减乘除等。用户可以通过构造函数设置最大值,然后使用`calculate`方法传入表达式来获取结果。这样,整个计算器的结构就比较清晰,易于理解和维护。
阅读全文