首頁  >  文章  >  後端開發  >  計算給定數字的冪的C程序

計算給定數字的冪的C程序

PHPz
PHPz轉載
2023-09-22 21:41:02898瀏覽

計算給定數字的冪的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:</p><p> ");
   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

以上是計算給定數字的冪的C程序的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除