ในบทความนี้ เราจะเข้าใจวิธีการคำนวณกำลังของตัวเลข กำลังของตัวเลขคำนวณโดยใช้การวนซ้ำแล้วคูณด้วยตัวมันเองหลายๆ ครั้ง
ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -
ป้อนข้อมูล
สมมติว่าข้อมูลที่เราป้อนคือ −
Number : 4 Exponent value : 5
ผลผลิต
ผลลัพธ์ที่ต้องการจะเป็นดังนี้ 4 5
The result is 1024
อัลกอริทึม
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
ตัวอย่างที่ 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;
my_result = 1;
while (my_exponent != 0) {
my_result *= my_input;
--my_exponent;
}
System.out.println("The result is = " + my_result);
}
} ผลลัพธ์
Required packages have been imported A reader object has been defined Enter the number : 4 Enter the exponent value : 5 The result is = 1024
ตัวอย่างที่ 2
ในที่นี้ มีการกำหนดจำนวนเต็มก่อนหน้านี้ และเข้าถึงและแสดงค่าบนคอนโซล
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);
}
} ผลลัพธ์
The number is defined as 4 and the exponent is defined as 5 The result is = 1024