C 語言中的對數計算程式


給定 n 的值作為輸入,任務是透過一個函式計算 Log n 的值並顯示它。

對數或 Log 是冪運算的反函式,這意味著要計算 log,必須將冪運算作為底數計算出來。

IF

  $$\log_b x\;\:=\: y\:than\:b^{y}=x$$

例如

 $$\log_2 64\;\:=\: 6\:than\:2^{6}=64$$

示例

Input-: Log 20
Output-: 4
Input-: Log 64
Output-: 6

演算法

Start
In function unsigned int log2n(unsigned int num)
   Step 1-> Return (num > 1) ? 1 + log2n(num / 2) : 0
In function int main()
   Step 1-> Declare and assign num = 20
   Print log2n(num)
Stop

示例

 即時演示

#include <stdio.h>
//We will be using recursive Approach used below is as follows
unsigned int log2n(unsigned int num) {
   return (num > 1) ? 1 + log2n(num / 2) : 0;
}
int main() {
   unsigned int num = 20;
   printf("%u
", log2n(num));    return 0; }

輸出

4

更新日期:2019-10-18

457 次瀏覽

開啟你的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.