Java程序计算一个数的幂


2022年3月2日, Learn eTutorial
1662

在这里,我们解释如何编写一个 Java 程序来计算数的幂。首先,我们需要从用户那里读取数字及其指数。然后我们将使用 while 循环计算数的幂。

如何在 Java 中读取数字?

要从用户那里读取一个整数,我们可以使用 Java Scanner 类中的 nextInt() 函数。

示例:number = sc.nextInt()

其中 sc 是 Scanner 类的对象。

如何在 Java 中计算一个数的幂?

首先,用 public 修饰符声明 PowerNum 类。然后打开 main() 函数,声明变量 number、power、result。将 result 设置为 1。从用户读取一个数字并将其保存到变量 number 中。从用户读取指数数字并将其保存到变量 p 中。然后将变量 i 初始化为 p 的值。然后使用 while 循环,检查条件 i 不等于零,计算结果为 result=result*number。将 i 减一并重复循环。然后显示结果。

算法

步骤 1:使用 public 修饰符声明 PowerNum 类

步骤 2:打开**main()**函数以启动程序,Java程序的执行从**main()**开始

步骤 3:声明变量 number、p 为整数,result 为长整数。

步骤 4:分配 result=1。

步骤 5:使用 scanner 类中的 nextInt() 方法从用户读取数字到变量 number 中。

步骤 6:使用 scanner 类中的 nextInt() 方法从用户读取指数到变量 p 中。

步骤 7:分配 i = p。

步骤 8:使用条件 i!=0 的 while 循环,然后执行步骤 9。

步骤 9:计算 result=result*number。

步骤 10:将 i 加一并重复步骤 8。

步骤 11:将结果显示为 number^p = result。

 

Java 源代码

                                          import java.util.Scanner;
public class PowerNum {
    public static void main(String[] args) {
        int number,p;
        long result = 1;
        Scanner sc = new Scanner(System.in);//Create the object of Scanner class.
        System.out.print("Enter the number:");
        number = sc.nextInt();//Read the number from the console
        System.out.print("Enter the Exponent:");
        p= sc.nextInt();//Read the Exponent from the console
        int i=p;
        while (i != 0)
        {
            result *= number;
            i--;
        }
        System.out.println(number+"^"+p+" = "+result);
    }
}
                                      

输出

OUTPUT 1

Enter the number:
2
Enter the Exponent:
2

2^2=4

OUTPUT 2

Enter the number:
5
Enter the Exponent:
3

5^3=125