How to find the power of a number in Java
In Java, you can use the Math.pow() method to calculate the power of a number. This method takes two parameters, with the first being the base and the second being the exponent. For example, to calculate 2 to the power of 3, you can write it like this:
double result = Math.pow(2, 3);
System.out.println(result); // 输出8.0
Alternatively, one can also calculate the n-th power of a number using a loop structure, 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
This method is more intuitive, but it may have performance issues with larger exponent values. Therefore, it is recommended to use the Math.pow() method to calculate the power.