C语言中的trunc()、truncf()、truncl()

这三个函数都用于删除小数点后的数字,并返回修改后的十进制数。

null

trunc(): 截断小数点后的双精度值,并给出整数部分作为结果。返回值和参数的类型为double。

语法: 双trunc(双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 " , trunc(x1) );
printf ( " Truncated value is %lf " , trunc(x2) );
// For negative values
printf ( " Truncated value is %lf " , trunc(x3) );
printf ( " Truncated value is %lf " , 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。获取浮点值,删除小数点后的数字,并返回修改后的浮点值。

语法: 浮球柄F(浮球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 " , truncf(x1) );
printf ( " Truncated value is %f " , truncf(x2) );
// For negative values
printf ( " Truncated value is %f " , truncf(x3) );
printf ( " Truncated value is %f " , 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()相同

语法: 长双特朗克(长双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 " , truncl(x1) );
printf ( " Truncated value is %Lf " , truncl(x2) );
// For negative values
printf ( " Truncated value is %Lf " , truncl(x3) );
printf ( " Truncated value is %Lf " , 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()函数。此函数的优点是,无论十进制值是什么,整数部分都保持不变。在 天花板还是地板 或舍入函数整数值改变,但在trunc函数中不改变。

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享