编写程序实现计算机的四则运算
时间: 2024-10-27 22:03:54 浏览: 8
CAC.rar_CaC偏程序_四则运算
编写一个简单的计算机四则运算程序,通常涉及基本的算术操作如加法、减法、乘法和除法。这通常是在控制台应用或基于某种编程语言的环境中完成。这里以Python为例,你可以创建一个函数来处理每个运算:
```python
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y != 0:
return x / y
else:
print("Error: Division by zero is not allowed.")
return None # 或者抛出异常
# 用户输入
operator = input("Enter operator (+, -, *, /): ")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if operator == '+':
result = add(num1, num2)
elif operator == '-':
result = subtract(num1, num2)
elif operator == '*':
result = multiply(num1, num2)
elif operator == '/':
result = divide(num1, num2)
else:
print("Invalid operator.")
print(f"Result of {num1} {operator} {num2} is: {result}")
阅读全文