Trong bài viết này, chúng ta sẽ tìm hiểu cách tính lũy thừa của một số trong Java. Lũy thừa được tính bằng cách sử dụng vòng lặp và nhân số đó với chính nó nhiều lần.
Dưới đây là minh họa:
Đầu vào
Giả sử đầu vào của chúng ta là:
Số: 4 Giá trị mũ: 5
Đầu ra
Kết quả mong đợi là 45:
Kết quả là 1024
Thuật toán
Bước 1 - BẮT ĐẦU Bước 2 – Khai báo hai giá trị nguyên: my_input và my_exponent Bước 3 - Đọc giá trị từ người dùng hoặc định nghĩa trước Bước 4 – Sử dụng vòng lặp while, nhân giá trị đầu vào với chính nó n lần (n là giá trị mũ). Lưu kết quả. Bước 5 - Hiển thị kết quả Bước 6 - DỪNG
Ví dụ 1: Nhập từ bàn phím
Ở đây, người dùng nhập giá trị dựa trên lời nhắc. Bạn có thể chạy ví dụ này trực tiếp trong công cụ coding ground.
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 = 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: Giá trị định nghĩa trước
Ở đây, số nguyên đã được định nghĩa trước và giá trị được truy xuất hiển thị trên console.
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 = 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