C 庫 - ldexp() 函式



C 庫的 ldexp() 函式,型別為 double,接受兩個引數,例如 (x 和 exponent),它以x乘以2的exponent次冪的形式返回結果。

語法

以下是 C 庫 ldexp() 函式的語法:

double ldexp(double x, int exponent)

引數

此函式接受兩個引數:

  • x - 這是表示有效數的浮點值。

  • exponent - 這是指數的值。

返回值

此函式返回 x * 2 exp

示例 1

以下是一個基本的 C 庫程式,用於說明 ldexp() 函式。

#include <stdio.h>
#include <math.h>

int main () {
   double x, ret;
   int n;

   x = 0.65;
   n = 3;
   ret = ldexp(x ,n);
   printf("%f * 2^%d = %f\n", x, n, ret);
   
   return(0);
}

輸出

以上程式碼產生以下結果:

0.650000 * 2^3 = 5.200000

示例 2

下面的程式使用尾數和指數計算球體的體積。

#include <stdio.h>
#include <math.h>

double sphere_volume(double radius) {
   int expo;
   double mantissa = frexp(radius, &expo);

   // Calculate volume = (4/3) * π * (mantissa * 2^exponent)^3
   double vol = (4.0 / 3.0) * M_PI * pow(ldexp(mantissa, expo), 3);

   return vol;
}

int main() {
   double sphere_radius = 5.0; 
   double sphere_vol = sphere_volume(sphere_radius);

   printf("Volume of sphere with radius %.2lf = %.6lf\n", sphere_radius, sphere_vol);
   return 0;
}

輸出

執行以上程式碼後,我們得到以下結果:

Volume of sphere with radius 5.00 = 523.598776

示例 3

要獲得 2x 的近似值,可以使用兩個函式:frexp() 返回尾數的值,而 ldexp() 用於返回結果。

#include <stdio.h>
#include <math.h>

double my_power_of_two(double x) {
   int expo;
   double mantis = frexp(x, &expo);
   return ldexp(mantis, expo);
}

int main() {
   double x = 3.96; 
   double approx_power_of_two = my_power_of_two(x);
   printf("Approximate 2^%.2lf = %.6lf\n", x, approx_power_of_two);
   return 0;
}

輸出

執行以上程式碼後,我們得到以下結果:

Approximate 2^3.96 = 3.960000
廣告

© . All rights reserved.