代码之家  ›  专栏  ›  技术社区  ›  Leo

java如何计算双变量中所有数字的和

  •  0
  • Leo  · 技术社区  · 13 年前

    我有这个代码,我能数出来 77! 数字然而,我有点困惑,如何计算双变量中所有数字的总和?

    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 回复  |  直到 13 年前
        1
  •  1
  •   asifsid88    13 年前

    BigInteger 是救援吗
    您可以使用BigInteger来处理此类情况

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

    输出:

    Result is ==> 13868394935526
    

    上面的例子将给你一个关于如何将两个数字相乘的想法。您可以使用自己的逻辑使代码正常工作:)

    用于添加

    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是不可变的,因此您需要重新分配值。

        2
  •  1
  •   Jayamohan    13 年前

    使用 BigInteger 如下所述,

    public static BigInteger factorial(BigInteger n) {
        {
            if (n.compareTo(BigInteger.ZERO) > 0)
                return BigInteger.ONE;
            return n.multiply(factorial(n.subtract(BigInteger.ONE)));
        }
    }
    
        3
  •  0
  •   HectorLector    13 年前

    您可以将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字符的错误处理。

        4
  •  -1
  •   Tom Ken    13 年前

    您可能应该使用 Long 或 BigInteger 对于您的阶乘计算,因为您可能会在使用double的计算中失去精度。您也不需要任何小数,这是浮点数字的主要使用情况。一旦你有了数字的整数表示,你就更容易对数字求和了。

    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;
    }