请分别用python和java两种语言编写输出一个计算器
时间: 2024-01-22 16:21:18 浏览: 110
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):
return x / y
# 输出菜单
print("选择运算:")
print("1、相加")
print("2、相减")
print("3、相乘")
print("4、相除")
# 获取用户输入
choice = input("输入你的选择(1/2/3/4):")
num1 = float(input("输入第一个数字:"))
num2 = float(input("输入第二个数字:"))
# 根据用户的选择进行运算
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
if num2 == 0:
print("除数不能为0")
else:
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("非法输入")
```
Java代码:
```java
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("选择运算:");
System.out.println("1、相加");
System.out.println("2、相减");
System.out.println("3、相乘");
System.out.println("4、相除");
int choice = scan.nextInt();
System.out.println("输入第一个数字:");
double num1 = scan.nextDouble();
System.out.println("输入第二个数字:");
double num2 = scan.nextDouble();
switch (choice) {
case 1:
System.out.println(num1 + " + " + num2 + " = " + (num1 + num2));
break;
case 2:
System.out.println(num1 + " - " + num2 + " = " + (num1 - num2));
break;
case 3:
System.out.println(num1 + " * " + num2 + " = " + (num1 * num2));
break;
case 4:
if (num2 == 0) {
System.out.println("除数不能为0");
} else {
System.out.println(num1 + " / " + num2 + " = " + (num1 / num2));
}
break;
default:
System.out.println("非法输入");
}
}
}
```
阅读全文