这三个函数均用于删除小数点后的数字并返回修改后的十进制数。
trunc():截断小数点后的双精度值,并给出整数部分作为结果。返回值和参数的类型为double。
用法:
double trunc(double x);
参数:
x:它以双精度值作为输入,然后将小数点后的值截断。
返回值:
它返回一个双精度值,其小数点后的值仅是0。
例子:
Input:3.5 Output:3.0 Input:-3.8 Output:-3.0
// C program to demonstrate
// trunc() function
#include <stdio.h>
// library containing trunc function
#include <math.h>
// 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。取一个浮点值,删除小数点后的数字并返回修改后的浮点。
用法:
float truncf(float x);
参数:
x:它以浮点值作为输入,然后将小数点后的值截断。
返回值:
它返回一个浮点数,其小数点后的值仅是0。
例子:
Input:4.5 Output:4.0 Input:-2.8 Output:-2.0
// C program to demonstrate truncf() function
#include <stdio.h>
#include <math.h>
// 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():长双精度的工作原理相似,函数上与trunc()和truncf()相同
用法:
long double truncl (long double x);
参数:
x:它使用一个长双精度值作为输入,然后将小数点后的值截断。
返回值:
它返回一个十进制值,其小数点后的值仅是0。
例子:
Input:4351.5 Output:4351.0 Input:-2008.8 Output:-2008.0
如果是正值:
// C program to demonstrate truncl() function
#include <stdio.h>
#include <math.h>
// 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
每当需要根据双精度数据类型计算整数部分时,就可以使用trunc()函数。此函数的优点是,无论十进制值是整数部分是什么,都保持不变。在ceil或floor或round函数中,整数值会更改,而在trunc函数中,整数值不会更改。
相关用法
注:本文由纯净天空筛选整理自agrawalmohak99大神的英文原创作品 trunc() , truncf() , truncl() in C language。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。