Java 有指数运算符吗?

Java 中有指数运算符吗?

例如,如果提示用户输入两个数字,并输入 32,正确答案应该是 9

import java.util.Scanner;
public class Exponentiation {


public static double powerOf (double p) {
double pCubed;


pCubed = p*p;
return (pCubed);
}


public static void main (String [] args) {
Scanner in = new Scanner (System.in);


double num = 2.0;
double cube;


System.out.print ("Please put two numbers: ");
num = in.nextInt();


cube = powerOf(num);


System.out.println (cube);
}
}
417215 次浏览

There is no operator, but there is a method.

Math.pow(2, 3) // 8.0


Math.pow(3, 2) // 9.0

FYI, a common mistake is to assume 2 ^ 3 is 2 to the 3rd power. It is not. The caret is a valid operator in Java (and similar languages), but it is binary xor.

There is the Math.pow(double a, double b) method. Note that it returns a double, you will have to cast it to an int like (int)Math.pow(double a, double b).

you can use the pow method from the Math class. The following code will output 2 raised to 3 (8)

System.out.println(Math.pow(2, 3));

The easiest way is to use Math library.

Use Math.pow(a, b) and the result will be a^b

If you want to do it yourself, you have to use for-loop

// Works only for b >= 1
public static double myPow(double a, int b){
double res =1;
for (int i = 0; i < b; i++) {
res *= a;
}
return res;
}

Using:

double base = 2;
int exp = 3;
double whatIWantToKnow = myPow(2, 3);

To do this with user input:

public static void getPow(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter first integer: ");    // 3
int first = sc.nextInt();
System.out.println("Enter second integer: ");    // 2
int second = sc.nextInt();
System.out.println(first + " to the power of " + second + " is " +
(int) Math.pow(first, second));    // outputs 9

In case if anyone wants to create there own exponential function using recursion, below is for your reference.

public static double power(double value, double p) {
if (p <= 0)
return 1;


return value * power(value, p - 1);
}