1. 程式人生 > >C++學習之floor函式,ceil函式和round函式

C++學習之floor函式,ceil函式和round函式

    做題時經常需要截斷小數點,向上取整或者向下取整,以前使用printf("%.2f",n);進行截斷操作,但如果資料不需要輸出,這種做法就行不通了,此時可以使用floor函式向下取整或者ceil函式向上取整。

標頭檔案:#include<cmath>

一.floor() 函式(向下取整)

1、函式原型:

double floor ( double x );
float floor ( float x );
long double floor ( long double x );

2、功能:返回一個小於傳入引數的最大整數

3、引數:x為將來被處理的數

4、返回值:返回不大於x的最大整數

5、注在C語言中只有double一個原型

6、示例程式

#include <cstdio>
#include <cmath> 
int main ()
{
	printf ("floor of 2.3 is %.1lf/n", floor (2.3) );
	printf ("floor of 2.6 is %.1lf/n", floor (2.6) );
	printf ("floor of -2.3 is %.1lf/n", floor (-2.3) );
	printf ("floor of -2.6 is %.1lf/n", floor (-2.6) );
	return 0;
}

輸出:

floor of 2.3 is 2.0
floor of 2.6 is 2.0
floor of -2.3 is -3.0
floor of -2.6 is -3.0

二.ceil()函式(向上取整)

1、函式原型:

double ceil ( double x );
float ceil ( float x );
long double ceil ( long double x );

2、功能:返回一個大於傳入引數的最小整數

3、引數:x為將來被處理的數

4、返回值:返回不小於x的最小整數

5、注在C語言中只有double一個原型

6、示例程式

#include <cstdio>
#include <cmath> 
int main ()
{
	printf ("ceil of 2.3 is %.1lf/n", ceil (2.3) );
	printf ("ceil of 2.6 is %.1lf/n", ceil (2.6) );
	printf ("ceil of -2.3 is %.1lf/n", ceil (-2.3) );
	printf ("ceil of -2.6 is %.1lf/n", ceil (-2.6) );
	return 0;
}

輸出:

ceil of 2.3 is 3.0
ceil of 2.6 is 3.0
ceil of -2.3 is -2.0
ceil of -2.6 is -2.0

三.round()函式 (四捨五入)

    C++中沒有round函式,需要自己建立(或者直接用floor函式和ceil函式模擬)。

示例程式:

#include <cstdio>
#include <cmath>
 double round(double r){
    return (r > 0.0) ? floor(r + 0.5) : ceil(r - 0.5);
}
int main ()
{
    printf ("round of 2.3 is %.1lf/n", round (2.3) );
    printf ("round of 2.6 is %.1lf/n", round (2.6) );
    printf ("round of -2.3 is %.1lf/n", round (-2.3) );
    printf ("round of -2.6 is %.1lf/n", round (-2.6) );
    return 0;
}

示例程式輸出:

round of 2.3 is 2.0
round of 2.6 is 3.0
round of -2.3 is -2.0
round of -2.6 is -3.0