ในบทความนี้ เราจะเรียนรู้วิธีการคำนวณกำลังของตัวเลขในภาษา Java การคำนวณกำลังทำได้โดยการใช้ลูปคูณตัวเลขด้วยตัวมันเองตามจำนวนเลขยกกำลัง
ตัวอย่างการทำงาน
อินพุต:
Number : 4 Exponent value : 5
เอาต์พุต:
The result is 1024
อัลกอริทึม
- เริ่มต้นโปรแกรม
- ประกาศตัวแปรจำนวนเต็ม 2 ตัวคือ
my_inputและmy_exponent - รับค่าจากผู้ใช้ หรือกำหนดค่าไว้ล่วงหน้า
- ใช้ลูป
whileคูณค่า input ด้วยตัวเองจำนวน n ครั้ง โดย n คือค่า exponent เก็บผลลัพธ์ไว้ - แสดงผลลัพธ์
- จบโปรแกรม
ตัวอย่างที่ 1: รับค่าจากผู้ใช้
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);
}
}
ตัวอย่างที่ 2: กำหนดค่าไว้ล่วงหน้า
public class Exponents {
public static void main(String[] args) {
int my_input = 4;
int 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);
}
}
ทั้งสองตัวอย่างจะให้ผลลัพธ์เป็น 1024 (45 = 1024)