Objective-C 除法总是返回 0
一些非常奇怪的事情正在发生。
float p1 = (6 / 100);
NSLog(@"p1 = %f", p1);
通过这两行代码,我得到以下输出:
p1 = 0.000000
为什么带有静态数字的简单除法不起作用!我有很多工作要做来解决分歧不起作用的问题!他妈的,我疯了吗?
Something really weird is happening.
float p1 = (6 / 100);
NSLog(@"p1 = %f", p1);
With those two lines of code I get the following output:
p1 = 0.000000
Why is a simple devide with static numbers not working! I have so much work to do to deal with divide not working! What he heck, am I crazy?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这些常量是整数,因此数学是用整数数学完成的。尝试
编辑 - @Stephen Canon 明智地指出,由于“p1”是一个
float
,因此没有理由不将整个计算作为float
进行:现在,由于这些都是常量,我想无论如何,这项工作很有可能由编译器完成。这也是事实,因为在某些现代机器(即英特尔架构)上,浮点处理器指令集非常奇怪,看起来明显的“优化”可能会或可能不会以这种方式工作。最后,我认为使用
float
常量进行操作可能(在某些情况下)会得到与使用double
进行操作不同的结果code> 值,然后转换为float
,如果为 true,这可能是决定一种方式或另一种方式的最佳参数。Those constants are integers, so the math is done with integer math. Try
edit — @Stephen Canon wisely points out that since "p1" is a
float
, there's no reason not to do the whole computation asfloat
:Now, since those things are both constants, I'd imagine there's a really good chance that the work is going to be done by the compiler anyway. It's also true that because on some modern machines (ie, Intel architecture), the floating-point processor instruction set is sufficiently weird that something that seems like an obvious "optimization" may or may not work out that way. Finally I suppose it might be the case that doing the operation with
float
constants could (in some cases) give a different result that doing the operation withdouble
values and then casting tofloat
, which if true would probably be the best argument for deciding one way or the other.由于计算机将这两个数字视为整数,因此执行整数数学运算并返回一个不带小数的整数 0 (0.06),然后转换为浮点数并存储在变量 p1 中。
至少一个数字(或两个数字)必须是浮点数才能进行浮点数学,当您将小数附加到数字时,您告诉计算机该常量是浮点数。
或者你可以输入它
Since both of these numbers are considered to be integers by the computer, integer math is performed and an integer is returned with no decimals which is 0 (0.06), then converted to float and stored in the variable p1.
A least one number (or both) has to be float to do floating point math, when you append a decimal to a number you tell the computer that the constant is a floating point number.
Or you could typecast it
您的作业包含一个整数除法,如果除数更大,则返回零。你可能打算这样做:
Your assignment contains an integer divide, which returns zero if the number you are dividing by is greater. You probably meant to do:
解决方法是将两个 int 变量相除并获得 float 结果。
解决方法:
注意:如果您更改顺序,此解决方案将不起作用。
编辑:
根据这个答案以前的答案你可以使用这个
A work around to divide two int variables and get float result.
The fix:
Note: if you change the order this solution won't work.
Edit:
According to this answer previous answer You can use this