C/C++去小數位取整、向下取整、向上取整與四捨五入
阿新 • • 發佈:2018-11-28
簡單整理一下這四種取整處理方法~
去小數位取整 (直接截去小數點後的資料)
型別轉換 (浮點型→整型)
當浮點型轉換為整型時,會截去小數點之後的資料,僅保留整數位。
double x=2.3;
int y=x;
cout<<y;
輸出:2
double x=-2.3;
int y=x;
cout<<y;
輸出:-2
向下取整(不大於x的最大整數)
floor() 函式(包含在標頭檔案< cmath >中)
函式原型:
double floor ( double x );
float floor ( float x );
long double floor ( long double x );
返回值: 不大於x的最大整數(但依然是浮點型)
printf("floor(%.1f) is %.1f\n",2.3,floor(2.3));
printf("floor(%.1f) is %.1f\n",2.8,floor(2.8));
printf("floor(%.1f) is %.1f\n",-2.3,floor(-2.3));
輸出:
floor(2.3) is 2.0
floor(2.8) is 2.0
floor(-2.3) is -3.0
向上取整(不小於x的最小整數)
ceil() 函式(包含在標頭檔案< cmath >中)
函式原型:
double ceil ( double x );
float ceil ( float x );
long double ceil ( long double x );
返回值: 不小於x的最小整數(但依然是浮點型)
printf("ceil(%.1f) is %.1f\n",2.3,ceil(2.3));
printf("ceil(%.1f) is %.1f\n",2.8,ceil(2.8));
printf("ceil(%.1f) is %.1f\n",-2.3,ceil(-2.3));
輸出:
ceil(2.3) is 3.0
ceil(2.8) is 3.0
ceil(-2.3) is -2.0
四捨五入
①浮點數的格式化輸出
控制浮點數的輸出格式,會自動進行四捨五入,這裡僅示範printf()
double pi=3.1415926;
printf("僅保留整數:%.f\n",pi);
printf("保留1位小數:%.1f\n",pi);
printf("保留2位小數:%.2f\n",pi);
printf("保留3位小數:%.3f\n",pi);
printf("保留4位小數:%.4f\n",pi);
輸出:
僅保留整數:3
保留1位小數:3.1
保留2位小數:3.14
保留3位小數:3.142
保留4位小數:3.1416
② round() 函式(包含在標頭檔案< cmath >中)
函式原型:
double round (double x);
float roundf (float x);
long double roundl (long double x);
返回值: x四捨五入後的整數(但依然是浮點型)
printf("round(%.1f) is %.1f\n",2.3,round(2.3));
printf("round(%.1f) is %.1f\n",2.5,round(2.5));
printf("round(%.1f) is %.1f\n",2.8,round(2.8));
printf("round(%.1f) is %.1f\n",-2.3,round(-2.3));
printf("round(%.1f) is %.1f\n",-2.8,round(-2.8));
輸出:
round(2.3) is 2.0
round(2.5) is 3.0
round(2.8) is 3.0
round(-2.3) is -2.0
round(-2.8) is -3.0
若編譯器不支援 round() 函式,可自行編寫
double round(double x)
{
return (x > 0.0) ? floor(x + 0.5) : ceil(x - 0.5);
}