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
相关推荐
Magnetic_h4 小时前
【iOS】方法与消息底层分析
笔记·学习·macos·ios·objective-c·cocoa
MaoJiu11 小时前
Flutter与原生端的通信
flutter·ios
iReaShare13 小时前
如何将 iPhone 备份到云端:完整指南
ios
小赵小赵福星高照~14 小时前
iOS UI视图面试相关
ui·ios·面试
杂雾无尘17 小时前
苹果高管揭示苹果背后秘密:苹果为何不涉足搜索引擎领域?
ios·apple
二流小码农17 小时前
鸿蒙开发:一键更新,让应用无需提交应用市场即可下载安装
android·ios·harmonyos
2501_915921431 天前
没有Mac如何完成iOS 上架:iOS App 上架App Store流程
android·ios·小程序·https·uni-app·iphone·webview
初级代码游戏2 天前
Maui劝退:用windows直接真机调试iOS,无须和Mac配对
macos·ios·配置·maui·热重载
fundroid2 天前
Swift 进军 Android,Kotlin 该如何应对?
android·ios
形影相吊2 天前
iOS防截屏实战
ios