栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Java中的十进制数字总和

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java中的十进制数字总和

您可能会舍入错误,但是我在这里看不到它。

final double first=198.4;//value extract by unmodifiable format methodfinal double second=44701.2;//value extract by unmodifiable format methodfinal double firstDifference= first+second; //I receive 44899.6final double calculatedDifference=44900.1; // comparison value for the flowfinal double error=firstDifference-calculatedDifference;// I receive -0.5if(Math.abs(error)<=0.5d){    // this branch is entered.    System.out.println(error);}

版画

-0.5

有两种方法可以更一般地处理此问题。您可以定义一个舍入误差,例如

 private static final double ERROR = 1e-9; if(Math.abs(error)<=0.5d + ERROR){

或使用舍入

final double firstDifference= round(first+second, 1); // call a function to round to one decimal place.

或使用固定精度的整数

final int first=1984;// 198.4 * 10final int second=447012; // 44701.2 * 10final int firstDifference= first+second;  //I receive 448996final int calculatedDifference=449001; // comparison value for the flowfinal int error=firstDifference-calculatedDifference;// I receive -5if(Math.abs(error)<=5){    // this branch is entered.    System.out.println(error);}

或者您可以使用BigDecimal。这通常是许多开发人员的首选解决方案,但恕我直言。;)



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/414013.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号