编写用户程序对加减乘除和四舍五入进行测试

zhangshengyuan1545 2012-06-18 07:46:54
编写类MathTool,该类包含两个数字的精确的加减乘除和四舍五入的静态方法。加的方法头如下:
public double add(double d1, double d2, int scale) //scale代表小数的位数,结果四舍五入。

public double add(double d1, double d2) //没有scale,默认值为3。

编写用户程序对加减乘除和四舍五入进行测试。
...全文
227 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
找工作中 2012-06-18
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]
给你一个四舍五入的。
int temp = 1;
(int)(temp + o.5)
[/Quote]
虽然不比楼上全,贵在精妙!
安特矮油 2012-06-18
  • 打赏
  • 举报
回复

public class Test {

public static void main(String[] args) {
System.out.println(add(1.0023D,2.03032,3));
System.out.println(subtract(1.0023D,2.03032,3));
System.out.println(multiply(1.0023D,2.03032,3));
System.out.println(divide(40,3,3));
}
public static double add(double d1, double d2, int scale){
BigDecimal b1 = new BigDecimal(d1);
String totStr = b1.add(new BigDecimal(d2)).toString();
int index = totStr.indexOf(".");
return b1.add(new BigDecimal(d2), new MathContext(scale + index, RoundingMode.HALF_UP)).doubleValue();
}
public static double subtract(double d1, double d2, int scale){
BigDecimal b1 = new BigDecimal(d1);
String totStr = b1.subtract(new BigDecimal(d2)).toString();
int index = totStr.indexOf(".");
return b1.subtract(new BigDecimal(d2), new MathContext(scale + index, RoundingMode.HALF_UP)).doubleValue();
}
public static double multiply(double d1, double d2, int scale){
BigDecimal b1 = new BigDecimal(d1);
String totStr = b1.multiply(new BigDecimal(d2)).toString();
int index = totStr.indexOf(".");
return b1.multiply(new BigDecimal(d2), new MathContext(scale + index, RoundingMode.HALF_UP)).doubleValue();
}
public static double divide(double d1, double d2, int scale){
BigDecimal b1 = new BigDecimal(d1);
return b1.divide(new BigDecimal(d2), scale, RoundingMode.HALF_UP).doubleValue();
}
}
看那边 2012-06-18
  • 打赏
  • 举报
回复
给你一个四舍五入的。
int temp = 1;
(int)(temp + o.5)

62,634

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧