如前所述,modf() 将一个数字分解为整数部分和小数部分。小数部分由函数返回,整数部分存储在传递给 modf() 作为参数的指针所指向的地址中。
此函数定义在 <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 is an integral type
modf() 参数
modf() 接受两个参数
- x - 要分解为两部分的值。
- intpart - 指向一个对象(与 x 类型相同)的指针,该对象的整数部分存储在该对象中,其符号与 x 相同。
modf() 返回值
modf() 函数返回传递给它的参数的小数部分。
示例 1: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;
}
运行程序后,输出将是
14.86 = 14 + 0.86 -31.201 = -31 + -0.201
示例 2: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;
}
运行程序后,输出将是
5 = 5 + 0
另请阅读