如何使用 float/double 的模数?
我正在为学校项目创建 RPN 计算器,但在使用模数运算符时遇到了问题。由于我们使用的是双精度数据类型,因此模数不适用于浮点数。例如,0.5 % 0.3 应该返回 0.2,但我遇到了被零除的异常。
该指令要求使用fmod()
。我到处寻找fmod()
,包括javadoc,但我找不到它。我开始认为这是我必须创建的一种方法?
编辑:嗯,奇怪。我刚刚再次插入这些数字,它似乎工作正常......但以防万一。使用浮点类型时,我需要注意 Java 中 mod 运算符的使用吗?我知道这样的事情不能在 C++ 中完成(我认为)。
I'm creating an RPN calculator for a school project and having trouble with the modulus operator. Since we're using the double data type, modulus won't work on floating-point numbers. For example, 0.5 % 0.3 should return 0.2, but I'm getting a division by zero exception.
The instruction says to use fmod()
. I've looked everywhere for fmod()
, including javadoc, but I can't find it. I'm starting to think it's a method I'm going to have to create?
Edit: Hmmm, strange. I just plugged in those numbers again and it seems to be working fine… but just in case. Do I need to watch out for using the mod operator in Java when using floating types? I know something like this can't be done in C++ (I think).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当你第一次运行它时,你可能犯了一个错字。
计算
0.5 % 0.3
按预期返回“0.2”(双精度)。Mindprod 很好地概述了 Java 中模数的工作原理。
You probably had a typo when you first ran it.
evaluating
0.5 % 0.3
returns '0.2' (A double) as expected.Mindprod has a good overview of how modulus works in Java.
与 C 不同,Java 允许对整数和浮点数使用 %,并且(与 C89 和 C++ 不同)它对所有输入(包括负数)都有明确定义:
来自 JLS §15.17.3:
因此,对于您的示例,0.5/0.3 = 1.6...。 q 与 0.5(被除数)同号(正),大小为 1(最大大小不超过大小 1.6...的整数),r = 0.5 - (0.3 * 1) = 0.2
Unlike C, Java allows using the % for both integer and floating point and (unlike C89 and C++) it is well-defined for all inputs (including negatives):
From JLS §15.17.3:
So for your example, 0.5/0.3 = 1.6... . q has the same sign (positive) as 0.5 (the dividend), and the magnitude is 1 (integer with largest magnitude not exceeding magnitude of 1.6...), and r = 0.5 - (0.3 * 1) = 0.2
我认为常规模数运算符在 Java 中可以实现此目的,但编码并不难。只需将分子除以分母,然后取结果的整数部分。将其乘以分母,然后用分子减去结果。
I thought the regular modulus operator would work for this in Java, but it can't be hard to code. Just divide the numerator by the denominator, and take the integer portion of the result. Multiply that by the denominator, and subtract the result from the numerator.
fmod
是用于处理浮点模数的标准 C 函数;我想你的消息来源是说 Java 处理浮点模数的方式与 C 的fmod
函数相同。在 Java 中,您可以像整数一样对双精度数使用%
运算符:fmod
is the standard C function for handling floating-point modulus; I imagine your source was saying that Java handles floating-point modulus the same as C'sfmod
function. In Java you can use the%
operator on doubles the same as on integers: