計算給定數的冪的 C 程式
從使用者那裡獲取基數和指數的兩個整數,並如以下所述計算冪。
示例
考慮以下內容來編寫 C 程式。
- 假設基數 =3
- 指數 = 4
- 冪=3*3*3*3
演算法
遵循下面給出的演算法 −
Step 1: Declare int and long variables. Step 2: Enter base value through console. Step 3: Enter exponent value through console. Step 4: While loop. Exponent !=0 i. Value *=base ii. –exponent Step 5: Print the result.
示例
以下程式解釋瞭如何在 C 語言中計算給定數的冪。
#include<stdio.h>
int main(){
int base, exponent;
long value = 1;
printf("Enter a base value:
");
scanf("%d", &base);
printf("Enter an exponent value: ");
scanf("%d", &exponent);
while (exponent != 0){
value *= base;
--exponent;
}
printf("result = %ld", value);
return 0;
}輸出
當執行上述程式時,它會產生以下結果 -
Run 1: Enter a base value: 5 Enter an exponent value: 4 result = 625 Run 2: Enter a base value: 8 Enter an exponent value: 3 result = 512
示例
如果我們想找到實數的冪,我們可以使用 pow 函式,它是在 math.h 中提供的一個預定義函式。
#include<math.h>
#include<stdio.h>
int main() {
double base, exponent, value;
printf("Enter a base value: ");
scanf("%lf", &base);
printf("Enter an exponent value: ");
scanf("%lf", &exponent);
// calculates the power
value = pow(base, exponent);
printf("%.1lf^%.1lf = %.2lf", base, exponent, value);
return 0;
}輸出
當執行上述程式時,它會產生以下結果 -
Enter a base value: 3.4 Enter an exponent value: 2.3 3.4^2.3 = 16.69
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP