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
相关推荐
恋猫de小郭3 小时前
Meta 宣布加入 Kotlin 基金会,将为 Kotlin 和 Android 生态提供全新支持
android·开发语言·ios·kotlin
泓博4 小时前
Objective-c把字符解析成字典
开发语言·ios·objective-c
Daniel_Coder4 小时前
Xcode 中常用图片格式详解
ios·xcode·swift
瓜子三百克5 小时前
Objective-C 路由表原理详解
开发语言·ios·objective-c
帅次5 小时前
Objective-C面向对象编程:类、对象、方法详解(保姆级教程)
flutter·macos·ios·objective-c·iphone·swift·safari
RyanGo7 小时前
iOS断点下载
ios·swift
蒙小萌19938 小时前
找工作-iOS开发-3年经验-AI协作开发
ios
丶皮蛋菌10 小时前
关于OC与Swift内存管理的解惑
ios
杂雾无尘11 小时前
掌握生死时速:苹果应用加急审核全攻略!
ios·swift·apple
HarderCoder11 小时前
Swift 6.2 中的 `@concurrent`
ios·swift