目标C的浮点数和除法数

编程入门 行业动态 更新时间:2024-10-23 18:24:41
本文介绍了目标C的浮点数和除法数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我非常怀疑使用浮点数进行除法, 这里是测试代码::

hi I have a big doubt of using floats for divisions, here the test code::

- (void)chuza { float option1 = 0; float option2 = 0; option1 = 100/50; option2 = 50/100; NSLog(@"option1 :: %f",option1); NSLog(@"option2 :: %f",option2); }

所以, 我得到:

2012-10-19 16:21:45.405 Project[2023:14f03] option1 :: 2.000000 2012-10-19 16:21:45.405 Project[2023:14f03] option2 :: 0.000000

所以我的问题是: 为什么浮动会像

so my question is: why would the float like when

分母>分子

denominator > numerator

但不喜欢

分子>分母??

numerator > denominator ??

谢谢!

推荐答案

这看起来很像整数除法,因为您要除以两个整数.当除以两个整数时(大多数情况下,如果不是全部,则全部编程语言),将忽略除法的其余部分.

That looks a lot like integer division to me since you are dividing two integer numbers. When dividing two integers (in most if not all programming languages) ignores the remainder of the division.

考虑如何评估这条线.首先计算整数除法,然后将整数结果转换为浮点数,以存储在float变量中.

Think of how that line is being evaluated. First the integer division is calculated and then the integer result is cast to a float to be stored in the float variable.

请注意,整数根本不存储任何小数,因此即使是0.999,因为整数也将是0.这不是舍入的问题.

这也不关乎分母大于分子.尝试除以100/30,结果将为3,而不是3.33333 ..就像浮点除法一样.

您可以通过将数字强制转换为浮点数或确保它们是浮点数来解决此问题.

You can solve this by casting the numbers to floats or making sure they are float numbers.

option2 = ((float)50/(float)100);

划分浮点数

option2 = 50.0f/100.0f;

更多推荐

目标C的浮点数和除法数

本文发布于:2023-11-29 21:56:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647736.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:除法   目标   浮点数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!