iOS 取整函数(四舍五入取整,向上向下取整,取最近整数)

取整用的函数主要在usr/include > math.h内

一、 四舍五入取整

函数方法如下:

c 复制代码
extern float roundf(float);
extern double round(double);
extern long double roundl(long double);

extern long int lroundf(float);
extern long int lround(double);
extern long int lroundl(long double);

举例:

c 复制代码
double rpValue = round(1.1);  // 1
double rpValue = round(1.5);  // 2

double rpValue = round(-1.4); // -1
double rpValue = round(-1.5); // -2
二、向上取值整(向x轴右侧取整)

函数方法如下:

c 复制代码
extern float ceilf(float x);
extern double ceil(double x);
extern long double ceill(long double x);

举例:

c 复制代码
double rpValue = ceil(-1.1); // -1
double rpValue = ceil(-1.9); // -1
double rpValue = ceil(1.1);  // 2
double rpValue = ceil(1.9);  // 2
三、向下取值整(向x轴左侧取整)

函数方法如下:

c 复制代码
extern float floorf(float x);
extern double floor(double x);
extern long double floorl(long double x);

举例:

c 复制代码
double rpValue = floor(-1.1); // -2
double rpValue = floor(-1.9); // -2
double rpValue = floor(1.1);  // 1
double rpValue = floor(1.9);  // 1
四、取最近整数(即在x轴向趋近最近整数,中间取整)

这里有个比较特殊的点:如果是x.5,这个值和两边整数比是在x轴上的中间位置,它会取接近的(偶数)!

函数方法如下:

c 复制代码
extern float nearbyintf(float x);
extern double nearbyint(double x);
extern long double nearbyintl(long double x);

extern float rintf(float x);
extern double rint(double x);
extern long double rintl(long double x);

extern long int lrintf(float x);
extern long int lrint(double x);
extern long int lrintl(long double x);

举例:

c 复制代码
double rpValue = rint(-1.1); // -1
double rpValue = rint(-1.5); // -2 向左取偶
double rpValue = rint(-1.9); // -2

double rpValue = rint(0.1);  // 0
double rpValue = rint(0.5);  // 0  向右取偶
double rpValue = rint(0.9);  // 1

double rpValue = rint(1.1);  // 1
double rpValue = rint(1.5);  // 2  向右取偶
double rpValue = rint(1.9);  // 2
相关推荐
90后的晨仔2 小时前
RxSwift 框架解析
前端·ios
可爱小仙子6 小时前
ios苹果系统,js 滑动屏幕、锚定无效
前端·javascript·ios
未来猫咪花7 小时前
# Flutter状态管理对比:view_model vs Riverpod
flutter·ios·android studio
咕噜企业签名分发-淼淼10 小时前
开发源码搭建一码双端应用分发平台教程:逐步分析注意事项
android·ios
键盘敲没电21 小时前
【IOS】GCD学习
学习·ios·objective-c·xcode
SY.ZHOU21 小时前
Significant Location Change
macos·ios·cocoa
吴Wu涛涛涛涛涛Tao1 天前
深入理解 Swift Codable:从基础到进阶
ios
Jouzzy1 天前
【iOS安全】iPhone X iOS 16.7.11 (20H360) WinRa1n 越狱教程
安全·ios·iphone
二流小码农2 天前
鸿蒙开发:实现一个标题栏吸顶
android·ios·harmonyos
season_zhu2 天前
iOS开发:关于日志框架
ios·架构·swift