C语言 目标 C. 将 int 转换为浮点数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5728998/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Objective C. Casting int to float
提问by
Sorry for such general question, but what is the best (as fast as possible and most safety) method to convert int to float in ObjC:
对于这样的一般问题,抱歉,但是在 ObjC 中将 int 转换为 float 的最佳(尽可能快和最安全)方法是什么:
First
第一的
int b = 10;
float a = [[NSNumber numberWithInt: b] floatValue]
There will be NSNumberinstance and messages numberWithInt, floatValuewill be send, right?
会有NSNumber实例和消息numberWithInt,floatValue会被发送,对吧?
Second
第二
int b = 10;
float a = (float) b;
C-style: this with call some subroutine?
C 风格:这与调用一些子程序?
Or some another way?
或者其他方式?
And why?
为什么?
采纳答案by Sherm Pendley
The C-style type cast is the clearest and easiest to read. If I happened to find code that created an NSNumberobject just to have it do the conversion, it would leave me wondering "Why did he do it that way? Is something happening here other than a plain old type conversion? What am I missing?"
C 风格的类型转换是最清晰和最容易阅读的。如果我碰巧找到创建NSNumber对象的代码只是为了让它进行转换,那会让我想知道“他为什么这样做?除了普通的旧类型转换之外,这里还发生了什么?我错过了什么?”
As for speed, I suspect that the simple type conversion would also be faster - the NSNumberobject will need to perform pretty much the same operations to do the conversion, and has the additional overhead of object creation and messaging on top of that. But as in all such cases, don't guess - measure. Profile your code to see if the conversion is a bottleneck that's significant enough to be worthy of your attention.
至于速度,我怀疑简单的类型转换也会更快——NSNumber对象需要执行几乎相同的操作来进行转换,并且在此之上还有对象创建和消息传递的额外开销。但在所有这些情况下,不要猜测 - 测量。分析您的代码,看看转换是否是一个足够重要的瓶颈,值得您注意。
回答by R.. GitHub STOP HELPING ICE
Since you ask about safety, the first thing you need to check is whether the value of your intfits in a float. Otherwise you're silently losing data. Unless the value is pretty small, it won't fit. I would switch to using doubleso you don't have to worry about this, then just make the assignment:
由于您询问安全性,因此您需要检查的第一件事是您的值是否int适合float. 否则你会默默地丢失数据。除非值非常小,否则它不适合。我会切换到使用,double这样您就不必担心这一点,然后只需进行分配:
double d;
d = i;
There is rarely any use for variables of type float, much like short...
类型变量很少有任何用处float,就像short...
回答by BoltClock
I really don't see the need for an NSNumberobject when a direct typecast between two numeric primitives is available. The NSNumberclass was not meant solely for type conversion anyway.
NSNumber当两个数字基元之间的直接类型转换可用时,我真的不认为需要一个对象。NSNumber无论如何,该类并不仅仅用于类型转换。

