0

私はこのコードを持っていて、なんとか数を数えることができました77!。しかし、double変数のすべての桁の合計をカウントする方法が少し混乱していますか?

77!=1.4518309202828584E113。また、ここでは整数データ型を使用できません。私は何をすべきか?

package org.kodejava.example.io;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;

public class Many {
    public static void main(String[] args) {
        System.out.println(factorial(77))
    }

    public static double factorial(double n) {
        if (n == 0) return 1;
        return n * factorial(n-1);
    }
}
4

4 に答える 4

1

BigIntegerBigInteger
を使用してそのようなケースを処理できます

BigInteger bigInteger1 = new BigInteger ("123456789");
BigInteger bigInteger2 = new BigInteger ("112334");
BigInteger bigIntResult = bigInteger1.multiply(bigInteger2); 
System.out.println("Result is  ==> " + bigIntResult);

出力:

Result is ==> 13868394935526

上記の例は、2 つの数を乗算する方法についてのアイデアを提供します。独自のロジックを使用して、コードを機能させることができます:)

追加用

BigInteger sum = BigInteger.valueOf(0);
for(int i = 2; i < 500; i++) {

        sum = sum.add(BigInteger.valueOf(i));

}

階乗の場合

public static BigInteger factorial(BigInteger n) {
    BigInteger result = BigInteger.ONE;

    while (!n.equals(BigInteger.ZERO)) {
        result = result.multiply(n);
        n = n.subtract(BigInteger.ONE);
    }

    return result;
}

BigInteger は不変であるため、値を再割り当てする必要があります。

于 2013-02-18T12:02:13.623 に答える
1

以下のようにBigIntegerを使用するのはどうでしょうか。

public static BigInteger factorial(BigInteger n) {
    {
        if (n.compareTo(BigInteger.ZERO) > 0)
            return BigInteger.ONE;
        return n.multiply(factorial(n.subtract(BigInteger.ONE)));
    }
}
于 2013-02-18T12:01:47.413 に答える
0

Double を String に変換してから、すべての char を int に変換し、これらの値を合計することができます。このような:

double x = 102.4000909;
String number = String.valueOf(x);
int sum = 0;
for(char c : number.toCharArray())
   sum += Integer.parseInt(String.valueOf(c));

System.out.println(sum);

DecimalSeperator char には ErrorHandling が必要になると思います。

于 2013-02-18T11:57:37.200 に答える
-1

double を使用すると計算の精度が失われる可能性があるため、階乗計算にはLongorを使用する必要があります。BigIntegerまた、浮動小数点数の主な使用例である小数値も必要ありません。数値の整数表現を取得すると、数字の合計がはるかに簡単になります。

String num = String.valueOf(bigInt);
int sum = 0;
for ( Character i : num.toCharArray() ) {
    sum += Integer.parseInt(String.valueOf(i));
}

これを行う別の方法は-

long n = factorial(6);
int sum = 0;
while (n > 0) {
    int p = n % 10;
    sum += p;
    n = n / 10;
}
于 2013-02-18T11:57:44.847 に答える