Java doubble类型的数据进行运算时的精度不准确的问题

题目描述

Calculate a + b. a and b are floating-point numbers.

输入

The input may contain several test cases.
In each test case, there are two floating-point numberss, a and b, separated by a space.
Input is terminated by EOF.

输出

For each test case, print out the sum of a and b. 

Each output number must be formatted as a floating point number with exactly two digit after the decimal point.

样例输入

12.123 45.6
45.12 87.44
23 45.9843
45.112 66.346

样例输出

57.72
132.56
68.98
111.46

解决:

package cugoj;
 /*遇到了java中doubble类型的数据进行运算时的精度不准确的问题
  * 1 2
  * 3.0
  * 1.1 2.2
  * 3.3000000000000003
  * 4.22 5.15
  * 9.370000000000001
  * 
  * */


import java.math.BigDecimal;
import java.util.Scanner;

public class Main2 {

    public static void main(String[] args)
    {
        // TODO Auto-generated method stub
        Scanner s1=new Scanner(System.in);

        
        while(s1.hasNext())
        {
            BigDecimal a=new BigDecimal(Double.toString(s1.nextDouble()));
            BigDecimal b=new BigDecimal(Double.toString(s1.nextDouble()));
            // 上面這一部分解決了double類型的数据运算精度不准确的问题

           if ("EOF".equals(s1.nextLine()))
           {
               break;
           }
           BigDecimal c=a.add(b);
           double ans=c.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
           //bigdecimal类型数据  保留两位小数  并且精度取值方式为“四舍五入”
           
            System.out.println(ans);
        }
        
        s1.close();

    }

}

猜你喜欢

转载自blog.csdn.net/qq_28619473/article/details/80356059