用java实现计算器 实现基本数学运算、函数等功能:加、减、乘、除、阶乘、正弦、余弦和指数运算。
时间: 2023-07-10 14:36:52 浏览: 110
好的,以下是Java实现计算器的示例代码,支持加、减、乘、除、阶乘、正弦、余弦和指数运算:
```java
import java.util.Scanner;
import java.lang.Math;
public class Calculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入算式:");
String expression = sc.nextLine();
double result = calculate(expression);
System.out.println("计算结果为:" + result);
}
public static double calculate(String expression) {
// 去掉空格
expression = expression.replaceAll(" ", "");
// 去掉末尾的等号
if (expression.endsWith("=")) {
expression = expression.substring(0, expression.length() - 1);
}
// 判断是否存在阶乘运算
if (expression.contains("!")) {
int n = Integer.parseInt(expression.substring(0, expression.length() - 1));
double result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
} else {
// 利用eval()函数计算表达式的值
return evaluate(expression);
}
}
public static double evaluate(String expression) {
return new Object() {
int pos = -1, ch;
void nextChar() {
ch = (++pos < expression.length()) ? expression.charAt(pos) : -1;
}
boolean eat(int charToEat) {
while (ch == ' ') nextChar();
if (ch == charToEat) {
nextChar();
return true;
}
return false;
}
double parse() {
nextChar();
double x = parseExpression();
if (pos < expression.length()) {
throw new RuntimeException("Unexpected: " + (char)ch);
}
return x;
}
double parseExpression() {
double x = parseTerm();
for (;;) {
if (eat('+')) {
x += parseTerm();
} else if (eat('-')) {
x -= parseTerm();
} else {
return x;
}
}
}
double parseTerm() {
double x = parseFactor();
for (;;) {
if (eat('*')) {
x *= parseFactor();
} else if (eat('/')) {
x /= parseFactor();
} else {
return x;
}
}
}
double parseFactor() {
if (eat('+')) return parseFactor();
if (eat('-')) return -parseFactor();
double x;
int startPos = this.pos;
if (eat('(')) {
x = parseExpression();
eat(')');
} else if ((ch >= '0' && ch <= '9') || ch == '.') {
while ((ch >= '0' && ch <= '9') || ch == '.') nextChar();
x = Double.parseDouble(expression.substring(startPos, this.pos));
} else if (ch >= 'a' && ch <= 'z') {
while (ch >= 'a' && ch <= 'z') nextChar();
String func = expression.substring(startPos, this.pos);
x = parseFactor();
switch (func) {
case "sin":
x = Math.sin(x);
break;
case "cos":
x = Math.cos(x);
break;
case "exp":
x = Math.exp(x);
break;
default:
throw new RuntimeException("Unknown function: " + func);
}
} else {
throw new RuntimeException("Unexpected: " + (char)ch);
}
if (eat('^')) {
x = Math.pow(x, parseFactor());
}
return x;
}
}.parse();
}
}
```
你可以尝试输入以下算式进行计算:
- 2+3
- 4-1
- 5*6
- 10/2
- 5!
- sin(30)
- cos(45)
- exp(2)
阅读全文