java 科学计算器代码
时间: 2023-06-23 19:47:57 浏览: 240
Java 计算器代码
以下是一个简单的 Java 科学计算器代码,包括基本的算术运算和三角函数:
```
import java.util.Scanner;
import java.lang.Math;
public class Calculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Scientific Calculator!");
System.out.println("Enter a number:");
double num1 = input.nextDouble();
System.out.println("Enter an operator (+, -, *, /, sin, cos, tan):");
String operator = input.next();
double result = 0;
switch(operator) {
case "+":
System.out.println("Enter another number:");
double num2 = input.nextDouble();
result = num1 + num2;
break;
case "-":
System.out.println("Enter another number:");
num2 = input.nextDouble();
result = num1 - num2;
break;
case "*":
System.out.println("Enter another number:");
num2 = input.nextDouble();
result = num1 * num2;
break;
case "/":
System.out.println("Enter another number:");
num2 = input.nextDouble();
result = num1 / num2;
break;
case "sin":
result = Math.sin(num1);
break;
case "cos":
result = Math.cos(num1);
break;
case "tan":
result = Math.tan(num1);
break;
default:
System.out.println("Invalid operator!");
break;
}
System.out.println("Result: " + result);
}
}
```
该代码使用了 `Scanner` 类获取用户输入,通过 `switch` 语句来判断用户选择的操作,并使用 `Math` 类中的方法来计算三角函数值。
阅读全文