English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Java complete list of examples
在此程序中,您将学习使用和不使用pow()函数来计算数字的幂。
public class Power { public static void main(String[] args) { int base = 3, exponent = 4; long result = 1; while (exponent != 0) { result *= base; --exponent; } System.out.println("Answer = "); + result); } }
When running the program, the output is:
Answer = 81
在此程序中,分别为base和exponent分配了值3和4。
使用while循环,我们将result乘以base,直到指数(exponent)变为零为止。
在这种情况下,我们result乘以基数总共4次,因此 result= 1 * 3 * 3 * 3 * 3 = 81。
public class Power { public static void main(String[] args) { int base = 3, exponent = 4; long result = 1; for (; exponent != 0;) --exponent) { result *= base; } System.out.println("Answer = "); + result); } }
When running the program, the output is:
Answer = 81
Here, we use a for loop instead of a while loop.
exponent is reduced after each iteration.1, then result is multiplied by base, exponent times.
If your exponent is negative, the two programs above are invalid. For this, you need to use the pow() function in the Java standard library.
public class Power { public static void main(String[] args) { int base = 3, exponent = -4; double result = Math.pow(base, exponent); System.out.println("Answer = "); + result); } }
When running the program, the output is:
Answer = 0.012345679012345678
In this program, we use Java's Math.pow() function to calculate the power of a given base.