在Objective-C中,如何将浮点舍入为最接近的整数:

例子:

float f = 45.698f;
int rounded = _______;
NSLog(@"the rounded float is %i",rounded);

应打印"四舍五入浮动为46"

推荐答案

建议的答案是:https://stackoverflow.com/a/4702539/308315


原始答案:

添加0.5后将其转换为整数.

所以

NSLog (@"the rounded float is %i", (int) (f + 0.5));

编辑:你要求的方式:

int rounded = (f + 0.5);


NSLog (@"the rounded float is %i", rounded);

Objective-c相关问答推荐

反编译ARM64和理解分支目标边界

如何从 Cocoa 的 NSDictionary 中获取特定键的值?

NSNumberFormatter 和 'th' 'st' 'nd' 'rd' (序数)数字结尾

如何在情节提要中为视图控制器提供标识符?

UIAlertView 按钮操作

Objective-C,如何获取 UTC 时区的当前日期?

在从 UIViewController 调用的非保留完成中引用 self 时,weakSelf/strongSelf 舞蹈真的有必要吗?

iOS UIImageView 缩小图像在 iPad 2 上产生锯齿图像

使用 arc4random() 时如何 Select 值的范围

使用 [NSBundle mainBundle] pathForResource: ofType:inDirectory: 访问文件

如何在目标 C 中创建单例类

isEqualTo: 和 isEqual 之间的区别:

Objective-C:如何从子类访问父属性?

Swift 3 - dynamic vs @objc

如何删除手势识别器

为什么不鼓励使用伞式框架?

iOS 上 64 位的 BOOL

在我滚动之前,数据不会加载到 UITableView 中

对 NSTimer 目标的弱引用以防止保留循环

`[super viewDidLoad]` 约定