Computer >> Máy Tính >  >> Lập trình >> Java

Tính lũy thừa của một số trong chương trình Java

Trong bài này, chúng ta sẽ hiểu cách tính lũy thừa của một số. Lũy thừa của một số được tính bằng một vòng lặp và nhân nó với chính nó nhiều lần.

Dưới đây là một minh chứng về điều tương tự -

Đầu vào

Giả sử đầu vào của chúng tôi là -

Number : 4
Exponent value : 5

Đầu ra

Đầu ra mong muốn sẽ là như sau, tức là 4 5

The result is 1024

Thuật toán

Step 1 - START
Step 2 – Declare two integer values namely my_input and my_exponent
Step 3 - Read the required values from the user/ define the values
Step 4 – Using a while loop, multiply the input value with itself for n number of times where n is the exponent value. Store the result.
Step 5- Display the result
Step 6- Stop

Ví dụ 1

Ở đây, đầu vào đang được người dùng nhập dựa trên lời nhắc. Bạn có thể thử trực tiếp ví dụ này trong công cụ nền tảng mã hóa của chúng tôi Tính lũy thừa của một số trong chương trình Java .

import java.util.Scanner;
public class Exponents {
   public static void main(String[] args) {
      int my_input , my_exponent;
      System.out.println("Required packages have been imported");
      Scanner my_scanner = new Scanner(System.in);
      System.out.println("A reader object has been defined ");
      System.out.print("Enter the number : ");
      my_input = my_scanner.nextInt();
      System.out.print("Enter the exponent value : ");
      my_exponent = my_scanner.nextInt();
      long my_result;
      my_result = 1;
      while (my_exponent != 0) {
         my_result *= my_input;
         --my_exponent;
      }
      System.out.println("The result is = " + my_result);
   }
}

Đầu ra

Required packages have been imported
A reader object has been defined
Enter the number : 4
Enter the exponent value : 5
The result is = 1024

Ví dụ 2

Ở đây, số nguyên đã được xác định trước đó và giá trị của nó được truy cập và hiển thị trên bảng điều khiển.

public class Exponents {
   public static void main(String[] args) {
      int my_input , my_exponent;
      my_input = 4;
      my_exponent = 5;
      System.out.println("The number is defined as " +my_input +" and the exponent is defined as " + my_exponent);
      long my_result;
      my_result = 1;
      while (my_exponent != 0) {
         my_result *= my_input;
         --my_exponent;
      }
      System.out.println("The result is = " + my_result);
   }
}

Đầu ra

The number is defined as 4 and the exponent is defined as 5
The result is = 1024