English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ modf() 函数使用方法及示例

C++ Biblioteca de Funções <cmath>

C ++中的modf()函数将数字分为整数和小数部分。

如前所述,modf(x, intptr)将数字分解为整数和小数部分。将浮点值 x 分解成小数和整数部分,每个都与 x 具有同样的符号。返回 x的带符号的小数部分,整数部分作为浮点值存储在 intptr 处。

此函数在<cmath>头文件中定义。

modf()原型[从C ++ 11标准开始]

double modf(double x, double* intpart);
float modf(float x, float* intpart);
long double modf(long double x, long double* intpart);
double modf(T x, double* intpart);  //T是整数类型

modf()参数

modf()具有两个参数:

  • x - 值被分成两部分。

  • intpart - 指向对象(类型与x相同)的对象,该部分以与x相同的符号存储整数部分。

modf()返回值

modf()函数返回传递给它的参数的小数部分。

Exemplo1:modf()如何工作?

#include <iostream>
#include <cmath>
using namespace std;
int main ()
{
	double x = 14.86, intPart, fractPart;
	fractPart = modf(x, &intPart);
	cout << x << " = " << intPart << ";" + " << fractPart << endl;
	x = -31.201;
	fractPart = modf(x, &intPart);
	cout << x << " = " << intPart << ";" + " << fractPart << endl;
	return 0;
}

Ao executar o programa, a saída será:

14.86 = 14 + 0.86
-31.201 = -31 + -0.201

Exemplo2:使用整数值作为第一个参数的modf()

#include <iostream>
#include <cmath>
using namespace std;
int main ()
{
	int x = 5;
	double intpart, fractpart;
	fractpart = modf(x, &intpart);
	cout << x << " = " << intpart << " " + " << fractpart << endl;
	return 0;
}

Ao executar o programa, a saída será:

5 = 5 + 0

C++ Biblioteca de Funções <cmath>