ฟังก์ชัน Power (ยกกำลัง) ใน C++
ฟังก์ชัน power ใช้หาค่ายกกำลังจากฐาน (base) และเลขชี้กำลัง (exponent) ผลลัพธ์คือฐานยกกำลังเลขชี้กำลัง
ตัวอย่าง: Base=2, Exponent=5 -> 2^5 = 32
ตัวอย่างโปรแกรม
#include <iostream>
using namespace std;
int main() {
int x, y, ans = 1;
cout << "Enter the base value: \n";
cin >> x;
cout << "Enter the exponent value: \n";
cin >> y;
for(int i = 0; i < y; i++)
ans *= x;
cout << x << " raised to the power " << y << " is " << ans;
return 0;
}
ผลลัพธ์
Enter the base value: 3 Enter the exponent value: 4 3 raised to the power 4 is 81
โปรแกรมรับค่า base และ exponent จากผู้ใช้ คำนวณยกกำลังด้วย for loop วน y รอบ คูณสะสมใน ans แล้วแสดงผล