我如何使用模数浮动/双? [英] How do I use modulus for float/double?
问题描述
我正在为学校项目创建一个RPN计算器。我在使用模数运算符时遇到问题。由于我们使用的是双数据类型,因此模数不适用于浮点数。例如,0.5%0.3应该返回0.2但是我得到除零异常。
I'm creating an RPN calculator for a school project. I'm 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.
指令说使用fmod()。我到处寻找fmod(),包括javadocs,但我找不到它。我开始认为这是一种我必须创建的方法?
The instruction says to use fmod(). I've looked everywhere for fmod(), including javadocs but I can't find it. I'm starting to think it's a method I'm going to have to create?
编辑:嗯,很奇怪。我只是再次插入这些数字,似乎工作正常......但为了以防万一。使用浮动类型时,是否需要注意在Java中使用mod运算符?我知道这样的事情不能在C ++中完成(我认为)。
edit: hmm, 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 using the mod operator in Java when using floating types? I know something like this can't be done in C++ (I think).
推荐答案
你第一次打错了运行它。
You probably had a typo when you first ran it.
评估 0.5%0.3
按预期返回'0.2'(双倍)。
evaluating 0.5 % 0.3
returns '0.2' (A double) as expected.
Mindprod有一个很好地了解模数如何工作 in Java。
Mindprod has a good overview of how modulus works in Java.
这篇关于我如何使用模数浮动/双?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!