1. 程式人生 > 其它 >實現兩個數之間的加減乘除

實現兩個數之間的加減乘除

import java.util.Scanner;
//實現兩個數之間的四則運算
public class Demo03 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);  //將scanner物件匯入
        double result = 0;
        
        //分別輸入計算的數字和符號
        System.out.print("請輸入第一個數字");
        double num1 = scanner.nextDouble();

        System.out.print(
"請輸入運算字元"); String operate = scanner.next(); System.out.print("請輸入第二個數字"); double num2 = scanner.nextDouble(); //switch語句來判斷計算符號 switch (operate){ case "+" : result = add(num1,num2); break; case "-" : result
= sub(num1,num2); break; case "*" : result = mult(num1,num2); break; case "/" : result = div(num1,num2); break; } System.out.println(result); } //定義加、減、乘、除四個方法 public static
double add(double num1, double num2){ return num1 +num2; } public static double sub(double num1, double num2){ return num1-num2; } public static double mult(double num1, double num2){ return num1*num2; } public static double div(double num1, double num2){ return num1/num2; } }