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
相关推荐
pop_xiaoli7 小时前
【iOS】autoreleasePool
ios·objective-c·cocoa
秋雨梧桐叶落莳10 小时前
iOS——ZARA仿写项目
学习·macos·ios·objective-c·cocoa
人月神话Lee10 小时前
【图像处理】二值化与阈值——从灰度到黑白的决策
ios·ai编程·图像识别
美狐美颜SDK开放平台13 小时前
美颜SDK接入流程详解:Android、iOS、鸿蒙兼容方案解析
android·人工智能·ios·华为·harmonyos·美颜sdk·视频美颜sdk
90后的晨仔14 小时前
Combine 操作符 —— 打造强大的数据处理管道
ios
90后的晨仔14 小时前
Combine 高级操作符:掌控数据流的节奏与方向
ios
90后的晨仔14 小时前
Combine 与 SwiftUI 集成:构建响应式 UI 的黄金搭档
ios
2501_9160074715 小时前
Xcode支持的编程语言、主要功能及使用指南
ide·vscode·macos·ios·个人开发·xcode·敏捷流程
MonkeyKing17 小时前
iOS 深入理解 UIView 与 CALayer:关系、渲染流程与坐标系
ios
君子木17 小时前
解决ios App的webview不支持<video>标签行内播放的问题(点击播放按钮后会直接全拼播放)
ios