请使用JAVA语言设计一个科学计算器
时间: 2024-02-28 17:55:08 浏览: 68
好的,下面是一个基本的Java科学计算器的实现示例:
```java
import java.util.Scanner;
public class ScientificCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double num1, num2, result = 0.0;
char operator;
System.out.println("欢迎使用科学计算器!");
System.out.print("请输入第一个数字: ");
num1 = scanner.nextDouble();
System.out.print("请选择运算符 (+, -, *, /, %, ^, !, sin, cos, tan, log, ln, sqrt, abs): ");
operator = scanner.next().charAt(0);
switch (operator) {
case '+':
System.out.print("请输入第二个数字: ");
num2 = scanner.nextDouble();
result = num1 + num2;
break;
case '-':
System.out.print("请输入第二个数字: ");
num2 = scanner.nextDouble();
result = num1 - num2;
break;
case '*':
System.out.print("请输入第二个数字: ");
num2 = scanner.nextDouble();
result = num1 * num2;
break;
case '/':
System.out.print("请输入第二个数字: ");
num2 = scanner.nextDouble();
if (num2 == 0) {
System.out.println("错误:除数不能为0");
return;
} else {
result = num1 / num2;
}
break;
case '%':
System.out.print("请输入第二个数字: ");
num2 = scanner.nextDouble();
result = num1 % num2;
break;
case '^':
System.out.print("请输入次方数: ");
num2 = scanner.nextDouble();
result = Math.pow(num1, num2);
break;
case '!':
result = factorial(num1);
break;
case 's':
result = Math.sin(num1);
break;
case 'c':
result = Math.cos(num1);
break;
case 't':
result = Math.tan(num1);
break;
case 'l':
if (scanner.next().charAt(1) == 'o') {
result = Math.log10(num1);
} else {
result = Math.log(num1);
}
break;
case 's':
result = Math.sqrt(num1);
break;
case 'a':
result = Math.abs(num1);
break;
default:
System.out.println("错误:无效的运算符");
return;
}
System.out.println(num1 + " " + operator + " = " + result);
}
public static double factorial(double n) {
if (n <= 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
}
```
这个程序实现了基本的加减乘除取余、次方、阶乘、三角函数、对数、根号、绝对值等科学计算功能。用户输入数字和运算符后,程序通过 switch 语句计算结果并输出。
阅读全文