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
相关推荐
missmisslulu10 小时前
电容笔值得买吗?2024精选盘点推荐五大惊艳平替电容笔!
学习·ios·电脑·平板
GEEKVIP12 小时前
手机使用技巧:8 个 Android 锁屏移除工具 [解锁 Android]
android·macos·ios·智能手机·电脑·手机·iphone
GEEKVIP12 小时前
如何在 Windows 10 上恢复未保存/删除的 Word 文档
macos·ios·智能手机·电脑·word·笔记本电脑·iphone
奇客软件12 小时前
iPhone使用技巧:如何恢复变砖的 iPhone 或 iPad
数码相机·macos·ios·电脑·笔记本电脑·iphone·ipad
奇客软件2 天前
如何从相机的记忆棒(存储卡)中恢复丢失照片
深度学习·数码相机·ios·智能手机·电脑·笔记本电脑·iphone
GEEKVIP2 天前
如何修复变砖的手机并恢复丢失的数据
macos·ios·智能手机·word·手机·笔记本电脑·iphone
一丝晨光2 天前
继承、Lambda、Objective-C和Swift
开发语言·macos·ios·objective-c·swift·继承·lambda
GEEKVIP2 天前
iPhone/iPad技巧:如何解锁锁定的 iPhone 或 iPad
windows·macos·ios·智能手机·笔记本电脑·iphone·ipad
KWMax2 天前
RxSwift系列(二)操作符
ios·swift·rxswift
Mamong3 天前
Swift并发笔记
开发语言·ios·swift