這三個函數均用於刪除小數點後的數字並返回修改後的十進製數。
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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。