这三个函数均用于删除小数点后的数字并返回修改后的十进制数。
trunc():截断小数点后的双精度值,并给出整数部分作为结果。返回值和参数的类型为double。
Syntax :
double trunc(double x);
Parameters:
x :It takes a double value as an input and then truncates the values after the decimal point.
Return Value :
It returns a double value whose values after the decimal point is 0 only.
例子:
Input : 3.5
Output : 3.0
Input : -3.8
Output : -3.0
// C program to demonstrate
// trunc() function
#include
// library containing trunc function
#include
// Driver function
int main()
{
// using trunc function which return
// Truncated value of the input
double x1 = 2.0, x2 = 3.9, x3 = -3.3, x4 = 4.9;
printf(" Truncated value is %lf \n", trunc(x1) );
printf(" Truncated value is %lf \n", trunc(x2) );
// For negative values
printf(" Truncated value is %lf \n", trunc(x3) );
printf(" Truncated value is %lf \n", trunc(x4) );
return 0;
}
Truncated value is 2.000000
Truncated value is 3.000000
Truncated value is -3.000000
Truncated value is 4.000000
truncf():它与trunc相同,区别在于它是float而不是double。取一个浮点值,删除小数点后的数字并返回修改后的浮点数。
Syntax :
float truncf(float x);
Parameters:
x :It takes a floating point value as an input and then truncates the values after the decimal point.
Return Value :
It returns a float whose values after the decimal point is 0 only.
例子:
Input : 4.5
Output : 4.0
Input : -2.8
Output : -2.0
// C program to demonstrate truncf() function
#include
#include
// Driver function
int main()
{
float x1 = 2.0, x2 = 3.9, x3 = -3.3, x4 = 4.9;
// using truncf function which return
// Truncated value of the input
printf(" Truncated value is %f \n", truncf(x1) );
printf(" Truncated value is %f \n", truncf(x2) );
// For negative values
printf(" Truncated value is %f \n", truncf(x3) );
printf(" Truncated value is %f \n", truncf(x4) );
return 0;
}
Truncated value is 2.000000
Truncated value is 3.000000
Truncated value is -3.000000
Truncated value is 4.000000
truncl():这对于long double而言工作类似,并且在功能上与trunc()和truncf()相同
Syntax :
long double truncl (long double x);
Parameters:
x :It takes a long double value as an input and then truncates the values after the decimal point.
Return Value :
It returns a decimal value whose values after the decimal point is 0 only.
例子:
Input : 4351.5
Output : 4351.0
Input : -2008.8
Output : -2008.0
如果是正值:
// C program to demonstrate truncl() function
#include
#include
// Driver function
int main()
{
long double x1 = 2.0, x2 = 3.9, x3 = -3.3, x4 = 4.9;
// using truncf function which return
// Truncated value of the input
printf(" Truncated value is %Lf \n", truncl(x1) );
printf(" Truncated value is %Lf \n", truncl(x2) );
// For negative values
printf(" Truncated value is %Lf \n", truncl(x3) );
printf(" Truncated value is %Lf \n", truncl(x4) );
return 0;
}
Truncated value is 2.000000
Truncated value is 3.000000
Truncated value is -3.000000
Truncated value is 4.000000
每当需要从double数据类型计算整数部分时,就可以使用trunc()函数。此函数的优点是,无论十进制值是整数部分是什么,都保持不变。在ceil或floor或round函数中,整数值会更改,而在trunc函数,整数值不会更改。