52

学校のプロジェクト用にRPN計算機を作成していますが、剰余演算子に問題があります。doubleデータ型を使用しているため、モジュラスは浮動小数点数では機能しません。たとえば、0.5%0.3は0.2を返すはずですが、ゼロ除算の例外が発生します。

指示は使用するように言っていますfmod()。javadocを含め、どこでも探しましたがfmod()、見つかりません。私はそれが私が作成しなければならない方法だと思い始めていますか?

編集:うーん、奇妙な。これらの番号をもう一度接続したところ、正常に機能しているようです…しかし念のため。フローティングタイプを使用する場合、Javaでmod演算子を使用することに注意する必要がありますか?私はこのようなことがC++ではできないことを知っています(私は思います)。

4

4 に答える 4

75

最初に実行したときにタイプミスがあった可能性があります。

評価0.5 % 0.3すると、期待どおりに「0.2」(ダブル)が返されます。

Mindprodには、Javaでモジュラスがどのように機能するかについての概要があります。

于 2010-06-01T02:59:41.540 に答える
46

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:

The result of a floating-point remainder operation is determined by the rules of IEEE arithmetic:

  • If either operand is NaN, the result is NaN.
  • If the result is not NaN, the sign of the result equals the sign of the dividend.
  • If the dividend is an infinity, or the divisor is a zero, or both, the result is NaN.
  • If the dividend is finite and the divisor is an infinity, the result equals the dividend.
  • If the dividend is a zero and the divisor is finite, the result equals the dividend.
  • In the remaining cases, where neither an infinity, nor a zero, nor NaN is involved, the floating-point remainder r from the division of a dividend n by a divisor d is defined by the mathematical relation r=n-(d·q) where q is an integer that is negative only if n/d is negative and positive only if n/d is positive, and whose magnitude is as large as possible without exceeding the magnitude of the true mathematical quotient of n and d.

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

于 2010-06-01T03:03:30.877 に答える
7

通常のモジュラス演算子はJavaでこれに使用できると思いましたが、コーディングするのは難しいことではありません。分子を分母で割って、結果の整数部分を取得するだけです。これに分母を掛け、分子から結果を引きます。

x = n/d
xint = Integer portion of x
result = n - d*xint
于 2010-06-01T02:59:08.297 に答える
3

fmod浮動小数点モジュラスを処理するための標準のC関数です。あなたの情報源は、JavaがCのfmod関数と同じように浮動小数点のモジュラスを処理すると言っていたと思います。Javaでは%、整数の場合と同じようにdoubleで演算子を使用できます。

int x = 5 % 3; // x = 2
double y = .5 % .3; // y = .2
于 2010-06-01T02:59:54.300 に答える