用java写一个简易的计算器包括科学计算器
时间: 2023-10-31 09:16:09 浏览: 91
java写的简单 计算器(包括科学计算器的部分功能)
好的,下面是Java代码实现简易计算器和科学计算器的功能。
简易计算器:
```java
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double num1, num2, result;
char operator;
System.out.print("请输入第一个数字:");
num1 = sc.nextDouble();
System.out.print("请输入运算符(+、-、*、/):");
operator = sc.next().charAt(0);
System.out.print("请输入第二个数字:");
num2 = sc.nextDouble();
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
default:
System.out.println("错误的运算符");
return;
}
System.out.println("结果:" + result);
}
}
```
科学计算器:
```java
import java.util.Scanner;
public class ScientificCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double num1, num2, result;
char operator;
int choice;
System.out.println("请选择计算模式:");
System.out.println("1.普通计算器");
System.out.println("2.科学计算器");
choice = sc.nextInt();
if (choice == 1) {
System.out.print("请输入第一个数字:");
num1 = sc.nextDouble();
System.out.print("请输入运算符(+、-、*、/):");
operator = sc.next().charAt(0);
System.out.print("请输入第二个数字:");
num2 = sc.nextDouble();
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
default:
System.out.println("错误的运算符");
return;
}
System.out.println("结果:" + result);
} else if (choice == 2) {
System.out.print("请输入数字:");
num1 = sc.nextDouble();
System.out.println("请选择函数:");
System.out.println("1.平方根");
System.out.println("2.正弦函数");
System.out.println("3.余弦函数");
System.out.println("4.正切函数");
int function = sc.nextInt();
switch (function) {
case 1:
result = Math.sqrt(num1);
break;
case 2:
result = Math.sin(num1);
break;
case 3:
result = Math.cos(num1);
break;
case 4:
result = Math.tan(num1);
break;
default:
System.out.println("错误的函数");
return;
}
System.out.println("结果:" + result);
} else {
System.out.println("错误的选择");
}
}
}
```
希望能够帮到你!
阅读全文