How to use the exponent operator in Java?
In Java, you can perform exponentiation operations using the pow method within the Math class. This method takes two parameters: the base and the exponent, and returns the value of the base raised to the power of the exponent.
For example, to calculate the cube of 2, you can use the following code:
double result = Math.pow(2, 3);
System.out.println(result); // 输出结果为8.0
Alternatively, you can also use the multiplication operator directly to perform exponentiation, for example:
int base = 2;
int exponent = 3;
int result = 1;
for (int i = 0; i < exponent; i++) {
result *= base;
}
System.out.println(result); // 输出结果为8