當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ frexp()用法及代碼示例

C++ 中的frexp() 函數將浮點數分解為其二進製有效數。

二進製有效數是一個浮點數,其絕對值(尾數)位於區間 [0.5, 1) 中,並且是 2 的整數 index 。

該函數在<cmath> 頭文件中定義。

數學上,

x = Binary significand * 2exponent

其中, index 存儲在 exp 指向的位置,二進製有效數是frexp() 返回的值。

frexp() 原型 [從 C++ 11 標準開始]

double frexp (double x, int* exp);
float frexp (float x, int* exp);
long double frexp (long double x, int* exp);
double frexp (T x, int* exp); // For integral type

frexp() 函數接受兩個參數並返回類型為 double , floatlong double 的二進製有效值。

參數:

  • x- 要分解的值。
  • exp- 指向要存儲 index 值的整數的指針。

返回:

frexp() 函數返回二進製有效數,其絕對值位於區間 [0.5, 1) 內。如果 x 為零,則有效數和 index 都為零。

frexp() 返回值
參數 (x) 二進製有效位 index
0 0 0
x >= 1 Positive Positive
x <= -1 Negative Positive
-1 < x < 0 Negative Negative
0 < x < 1 Positive Negative

示例 1:frexp() 函數在 C++ 中如何工作?

#include <iostream>
#include <cmath>

using namespace std;

int main ()
{
	double x = 6.81, significand;
	int *exp;
	significand = frexp(x , exp);
	cout << x << " = " << significand << " * 2^" << *exp << endl;

	return 0;
}

運行程序時,輸出將是:

6.81 = 0.85125 * 2^3

示例 2:frexp() 具有整數類型的函數

#include <iostream>
#include <cmath>

using namespace std;

int main ()
{
	double significand;
	int *exp, x = 25;
	significand = frexp (x , exp);
	cout << x << " = " << significand << " * 2^" << *exp << endl;
	return 0;
}

運行程序時,輸出將是:

25 = 0.78125 * 2^5

相關用法


注:本文由純淨天空篩選整理自 C++ frexp()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。