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
相关推荐
韩曙亮19 分钟前
【Flutter】Flutter 中的 Android / iOS 特殊配置 ① ( 网络权限配置 | HTTP 明文传输配置 | 应用名称配置 )
android·网络·flutter·http·ios·网络权限
人月神话-Lee3 小时前
【图像处理】颜色空间——RGB之外的世界
图像处理·人工智能·ios·ai编程·swift·rgb·颜色空间
CocoaKier3 小时前
苹果后台年龄分级填写错误,可能导致审核被拒!
ios·apple
月诸清酒3 小时前
Codex 现在能在浏览器里跑 iOS 模拟器了
ios
武子康4 小时前
调查研究-159 Apple WWDC 2026 定档 6/8-12:Siri 与 AI 升级,可能是苹果最关键的一次
人工智能·深度学习·ios·ai·chatgpt·apple·wwdc
2601_961194025 小时前
27考研资料|百度网盘|夸克网盘
android·xml·考研·ios·iphone·xcode·webview
2601_955767425 小时前
2026年iPhone17AR护眼膜推荐:悟赫德
人工智能·科技·ios·iphone·圆偏振光
秋雨梧桐叶落莳15 小时前
iOS——NSUserDefaults学习
学习·macos·ios·objective-c·cocoa
2601_9557674217 小时前
iPhone 17 OLED 屏幕偏振光学分析 & AR 镀膜与双护技术实践解析
人工智能·科技·ios·iphone·圆偏振光
人月神话Lee20 小时前
【图像处理】颜色空间——RGB之外的世界
ios·ai编程·图像识别