好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

java中求高精度除法,要求保留N位小数

求高精度除法,要求保留N位小数

题目要求

高精度除法,要求保留N位小数(四舍五入),并且当整数部分为0时去除0的显示

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

import java.math.BigDecimal;

import java.util.Scanner;

public class BD

{

     public static void main(String[] args)

     {

         Scanner scanner = new Scanner(System.in);

         while (scanner.hasNext())

        {

            BigDecimal a = scanner.nextBigDecimal();

            BigDecimal b = scanner.nextBigDecimal();

            int n = scanner.nextInt();

            System.out.println(a.divide(b, n, BigDecimal.ROUND_HALF_UP).toString().replaceFirst( "^0*" , "" ));

        }

    }

}

java 大数处理和高精度小数处理(so easy)

试用范围:当对数据处理时,最大的long型不能装下,这时候就需要采用大数BigInteger来解决

简单的例子:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

package cn.hncu.BigNUM;

import java.math.BigInteger;

public class bigIntegerdemo {

  public static void main(String[] args) {

    BigInteger sum=jc( 100 ); //计算100的阶乘是很大的数,long是超范围的,所以采用Java 中的大数处理,BigInteger

    System.out.println(sum);

  }

  private static BigInteger jc( int n) {

   BigInteger s=BigInteger.valueOf( 1 ); //必须先变成bigInteger类型的才能进行运算

   for ( int i= 1 ;i<=n;i++){

    s=s.multiply(BigInteger.valueOf(i)); //BigInteger的函数乘法也要用到函数

   }

   return s; 

  }

}

若是采用double 值来操作,就会可能出现0.9999等一些近似值

部分简单代码

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

package cn.hncu.BigNUM;

import java.math.BigDecimal;

public class BigDecimal1 {

//高精度数处理

  public static void main(String[] args) {

    double sum= 0 ;

    for ( int i= 0 ;i< 10 ;i++){

     sum=sum+ 0.1 ;

    } //0.9999999999999999

    System.out.println(sum); //这样的结果,是按着科学计算法来算,如double 四位,用二进制来表示,因为不可能完全能够表示,所以去了近似值

     add();

  }

 

  private static void add() {

   BigDecimal be = new BigDecimal( 0 ); 

   for ( int i= 0 ;i< 10 ;i++){

    be=be.add( new BigDecimal( 0.1 )); //变成高精度后,会运算精准

   }

   System.out.println(be.doubleValue()); //1.0 

  }

}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文链接:https://HdhCmsTestcnblogs测试数据/catdrivedragon/p/3966273.html

查看更多关于java中求高精度除法,要求保留N位小数的详细内容...

  阅读:16次