กำลังของตัวเลขสามารถคำนวณได้เป็น x^y โดยที่ x คือตัวเลข และ y คือกำลังของตัวเลขนั้น
ตัวอย่างเช่น
Let’s say, x = 2 and y = 10 x^y =1024 Here, x^y is 2^10
โปรแกรมหากำลังโดยใช้การเรียกซ้ำมีดังนี้
ตัวอย่าง
#include <iostream>
using namespace std;
int FindPower(int base, int power) {
if (power == 0)
return 1;
else
return (base * FindPower(base, power-1));
}
int main() {
int base = 3, power = 5;
cout<<base<<" raised to the power "<<power<<" is "<<FindPower(base, power);
return 0;
} ผลลัพธ์
3 raised to the power 5 is 243
ในโปรแกรมข้างต้น ฟังก์ชัน findPower() เป็นฟังก์ชันแบบเรียกซ้ำ หากกำลังเป็นศูนย์ ฟังก์ชันจะคืนค่า 1 เนื่องจากตัวเลขใดๆ ที่ยกกำลัง 0 คือ 1 หากกำลังไม่ใช่ 0 ฟังก์ชันจะเรียกตัวเองซ้ำๆ ซึ่งแสดงให้เห็นโดยใช้ข้อมูลโค้ดต่อไปนี้
int FindPower(int base, int power) {
if (power == 0)
return 1;
else
return (base * findPower(base, power-1));
} ในฟังก์ชัน main() ฟังก์ชัน findPower() จะถูกเรียกใช้ในขั้นต้นและแสดงพลังของตัวเลข
ซึ่งสามารถเห็นได้ในข้อมูลโค้ดด้านล่าง
3 raised to the power 5 is 243