如何在代码中添加指数

时间:2016-11-06 03:12:40

标签: java

import java.util.Scanner;

public class Calculator
{
    public static void main(String[] args )
    {
       Scanner userInput = new Scanner(System.in);
       String operator;
       double num1,num2,answer = 0;

       System.out.println("Enter first number: ");
       num1 = userInput.nextDouble();
       System.out.println("Enter operator: ");
       operator = userInput.next();
       System.out.println("Enter second number: ");
       num2 = userInput.nextDouble();

       if (operator.equals ("+")){
          answer = num1 + num2;
       }
       else if (operator.equals ("-")){
          answer = num1 - num2;
       }
       else if (operator.equals ("*")){
          answer = num1 * num2;
       }
       else if (operator.equals ("/")){
          answer = num1 / num2;
       }
       System.out.println("First number:" + num1);
       System.out.println("Operator:" + operator);
       System.out.println("Second number:" + num2);
       System.out.println("Answer: " + answer);
   }
}

1 个答案:

答案 0 :(得分:0)

使用此功能:

   Math.pow(x, y)

以这种方式:放置代码

   else if (operator.equals ("^")){
      answer = Math.pow(num1, num2);
   }

在你现在的代码之后

   else if (operator.equals ("/")){
      answer = num1 / num2;
   }

因此这部分代码将是

   else if (operator.equals ("/")){
      answer = num1 / num2;
   }
   else if (operator.equals ("^")){
      answer = Math.pow(num1, num2);
   }