Java函数示例-如何使用数学函数实现计算器程序
发布时间:2023-07-06 08:45:20
计算器程序是一个常见的应用程序,可以通过输入数学表达式来进行计算并得到结果。在Java中,可以使用数学函数来实现计算器程序。下面是一个示例,展示了如何使用数学函数来实现一个简单的计算器程序。
import java.util.Scanner;
import java.lang.Math;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter the second number: ");
double num2 = scanner.nextDouble();
System.out.println("Select an operation:");
System.out.println("1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Multiplication");
System.out.println("4. Division");
System.out.println("5. Power");
int choice = scanner.nextInt();
double result = 0;
switch(choice) {
case 1:
result = num1 + num2;
break;
case 2:
result = num1 - num2;
break;
case 3:
result = num1 * num2;
break;
case 4:
result = num1 / num2;
break;
case 5:
result = Math.pow(num1, num2);
break;
default:
System.out.println("Invalid choice");
}
System.out.println("Result: " + result);
scanner.close();
}
}
在这个程序中,我们首先使用Scanner对象来获取用户输入的两个数字。然后,我们通过打印菜单的方式让用户选择要进行的操作,可以选择加法、减法、乘法、除法或幂运算。
根据用户的选择,我们使用switch语句来执行相应的操作,最后将结果打印出来。在进行幂运算时,我们使用了Math库中的pow函数来计算结果。
这个示例程序展示了如何使用数学函数来实现一个简单的计算器程序。根据需要,你可以扩展这个程序,添加更多的功能和操作。
