java小数计算器,java计算器.

Java codepublic class Arith

{

//默认除法运算精度

private static final int DEF_DIV_SCALE = 10;

//构造器私有,让这个类不能实例化

private Arith() {}

//加法运算

public static double add(double v1,double v2)

{

BigDecimal b1 = BigDecimal.valueOf(v1);

BigDecimal b2 = BigDecimal.valueOf(v2);

return b1.add(b2).doubleValue();

}

//精确的减法运算。

public static double sub(double v1,double v2)

{

BigDecimal b1 = BigDecimal.valueOf(v1);

BigDecimal b2 = BigDecimal.valueOf(v2);

return b1.subtract(b2).doubleValue();

}

//精确的乘法运算。

public static double mul(double v1,double v2)

{

BigDecimal b1 = BigDecimal.valueOf(v1);

BigDecimal b2 = BigDecimal.valueOf(v2);

return b1.multiply(b2).doubleValue();

}

//(相对)精确的除法运算

//当发生除不尽的情况时,精确到

//小数点以后10位的数字四舍五入。

public static double div(double v1,double v2)

{

BigDecimal b1 = BigDecimal.valueOf(v1);

BigDecimal b2 = BigDecimal.valueOf(v2);

return b1.divide(b2 , DEF_DIV_SCALE , BigDecimal.ROUND_HALF_UP).doubleValue();

}

public static void main(String[] args)

{

System.out.println("0.05 + 0.01 = " + Arith.add(0.05 , 0.01));

System.out.println("1.0 - 0.42 = " + Arith.sub(1.0 , 0.42));

System.out.println("4.015 * 100 = " + Arith.mul(4.015 , 100));

System.out.println("123.3 / 100 = " + Arith.div(123.3 , 100));

}

}

------解决方案--------------------

import java.io.*;

class Op

{

private float i;

private float j;

public Op(float i,float j)

{

this.i=setI(i);

this.j=setJ(j);

}

public float setI(float i)

{

return i;

}

public float setJ(float j)

{

return j;

}

public void plus()

{

System.out.println("i+j = "+(i+j));

}

public void sub()

{

System.out.println("i-j = "+(i-j));

}

public void mul()

{

System.out.println("i*j = "+(i*j));

}

public void div()

{

System.out.println("i/j = "+(i/j));

}

};

public class Calculator

{

public static void main(String args[])

{

BufferedReader buf=new BufferedReader(new InputStreamReader(System.in));

int i=0;

int j=0;

String str=null;

String s=null;

try

{

System.out.println("请输入第一个数字");

str=buf.readLine();

i=Integer.parseInt(str);

label1:

for(;true;)

{

System.out.println("请输入第二个数字");

str=buf.readLine();

j=Integer.parseInt(str);

Op o=new Op(i,j);

label2:

for(;true;)

{

System.out.println("请输入所需的操作:加,减,乘,除");

s=buf.readLine();

if(s.equals("+"))

{

o.plus();

}

else if(s.equals("-"))

{

o.sub();

}

else if(s.equals("*"))

{

o.mul();

}

else if(s.equals("/"))

{

if(j==0)

{

System.out.println("请输入一个不为零的除数");

continue label1;

}

else

{

o.div();

}

}

else

{

System.out.println("请输入正确的操作");

continue label2;

}

break;

}

break;

}

}

catch (Exception e)

{

System.out.println("输入的数据格式有误,请重新输入一个数字");

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值