在C++中,modf()是用于数学计算的预定义函数。 math.h是各种数学功能所需的头文件。该库中所有可用的函数都将double作为参数,并返回double作为结果。
modf()函数将给定参数分为两部分,一个是整数,另一个是小数。整数部分存储在指针所指向的内存地址中,该指针作为函数的第二个参数传递,小数部分由函数返回。
句法:
double modf(k, &p)
- k: It is value which is going to be breaked into two parts.
- p: It is pointer which points to the integer part of k after breaking.
Return:
- The function returns the fractional value of k.
Error:
- No particular error raised by this function.
Parameters:
- 如果传递的不是浮点数,双精度数或整数,则返回类型错误。
// CPP program to demonstrate // exception of this function #include
using namespace std; int main() { // Take any value double p, fraction; string k = "5.06"; // Breaks k into two parts fraction = modf(k, &p); cout << "Integer Value = " << p << endl << "Fraction Value = " << fraction << endl; return 0; } 输出:
prog.cpp:13:23: error: no matching function for call to 'modf(std::__cxx11::string&, double*)' fraction = modf(k, &p); ..... /usr/include/c++/5/cmath:395:3: note: candidate: float std::modf(float, float*) modf(float __x, float* __iptr)
与该函数相关的异常:
Note: k and p must be of same data type.
例子:
- 传递double(float)值作为参数:
// CPP program to demonstrate // modf() function #include
using namespace std; int main() { // Take any value double k = 5.06, p, fraction; // Breaks k into two parts fraction = modf(k, &p); cout << "Integer Value = " << p << endl << "Fraction Value = " << fraction << endl; return 0; } 输出
Integer Value = 5 Fraction Value = 0.06
- 传递整数值作为参数:
// CPP program to demonstrate // modf() function #include
using namespace std; int main() { // Taking positive value double k = 8, p, fraction; // Breaks k into two parts fraction = modf(k, &p); cout << k << " =>"; cout << "\tInteger Value = " << p << endl << "\tFraction Value = " << fraction << endl; // Taking negative value k = -8; fraction = modf(k, &p); cout << k << " =>"; cout << "\tInteger Value = " << p << endl << "\tFraction Value = " << fraction << endl; return 0; } 输出
8 => Integer Value = 8 Fraction Value = 0 -8 => Integer Value = -8 Fraction Value = -0
注意:如上述代码所示,正值给出正输出,负值给出负输出。因此,小数和整数都与参数中的给定值具有相同的符号。
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。