English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Java

Java 流程控制

Java 数组

Java 面向对象(I)

Java 面向对象(II)

Java 面向对象(III)

Gestion des exceptions Java

Java 列表(List)

Java Queue(队列)

Java Map集合

Java Set集合

Java 输入输出(I/O)

Java Reader/Writer

Java 其他主题

Java程序来计算数字的幂

Java complete list of examples

在此程序中,您将学习使用和不使用pow()函数来计算数字的幂。

Example1:使用while循环计算数字的幂

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。

Example2:使用for循环计算数字的幂

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.

Example3: calculate the power of a number using the pow() function

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.

Java complete list of examples