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();

    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值