用java生成一个计算器代码包括加减乘除乘方和根
时间: 2024-09-12 18:08:15 浏览: 43
在Java中创建一个基本的四则运算计算器,以及支持乘方和开方的功能,可以按照下面的步骤编写:
```java
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("欢迎使用简易计算器!");
while (true) {
System.out.println("\n请选择操作:");
System.out.println("1. 加法");
System.out.println("2. 减法");
System.out.println("3. 乘法");
System.out.println("4. 除法");
System.out.println("5. 幂运算");
System.out.println("6. 开平方");
System.out.print("7. 退出\n");
int choice = scanner.nextInt();
double num1, num2;
if (choice == 7) { // 退出选项
break;
} else if (choice >= 1 && choice <= 4) {
System.out.print("请输入第一个数字:");
num1 = scanner.nextDouble();
System.out.print("请输入第二个数字:");
num2 = scanner.nextDouble();
switch (choice) {
case 1: // 加法
System.out.println(num1 + " + " + num2 + " = " + add(num1, num2));
break;
case 2: // 减法
System.out.println(num1 + " - " + num2 + " = " + subtract(num1, num2));
break;
case 3: // 乘法
System.out.println(num1 + " * " + num2 + " = " + multiply(num1, num2));
break;
case 4: // 除法
if (num2 != 0) {
System.out.println(num1 + " / " + num2 + " = " + divide(num1, num2));
} else {
System.out.println("错误! 除数不能为零.");
}
break;
}
} else if (choice == 5) { // 幂运算
System.out.print("请输入底数:");
num1 = scanner.nextDouble();
System.out.print("请输入指数:");
num2 = scanner.nextDouble();
System.out.println(num1 + " ^ " + num2 + " = " + power(num1, num2));
} else if (choice == 6) { // 开平方
System.out.print("请输入一个非负数:");
num1 = scanner.nextDouble();
if (num1 >= 0) {
System.out.println("sqrt(" + num1 + ") = " + Math.sqrt(num1));
} else {
System.out.println("错误! 只能计算非负数的平方根.");
}
} else {
System.out.println("无效的选择, 请重新输入.");
}
System.out.println();
}
scanner.close();
}
// 数学函数实现
private static double add(double a, double b) {
return a + b;
}
private static double subtract(double a, double b) {
return a - b;
}
private static double multiply(double a, double b) {
return a * b;
}
private static double divide(double a, double b) {
return a / b;
}
private static double power(double base, double exponent) {
return Math.pow(base, exponent);
}
}
```
阅读全文