java加减乘除表达式_计算四则运算表达式(Java语言实现)

private staticFraction cal(String s) {

Stack stack = new Stack();for (int i = 0; i < s.length(); i++) {char c =s.charAt(i);boolean flag = false;int tmp = 0;if (c == ' ')continue;while(is_num(c)) {

tmp*= 10;

tmp+= (c - '0');

i++;

c=s.charAt(i);

flag= true;

}if(flag) {

i--;

stack.push(new Fraction(tmp, 1));

tmp= 0;

}else{

Fraction x1=stack.pop();

Fraction x2=stack.pop();

Fraction ans= new Fraction(1, 1);if (c == '*')

ans=x1.mul(x2);else if (c == '-')

ans=x2.sub(x1);else if (c == '+')

ans=x1.add(x2);else if (c == '/')

ans=x2.div(x1);

stack.push(ans);

}

}returnstack.pop();

}private static boolean is_num(charc) {if (c >= '0' && c <= '9')return true;return false;

}static classFraction {private intnumerator, denominator;public Fraction(int numerator, intdenominator) {this.numerator =numerator;this.denominator =denominator;

}int gcd(int x, inty) {while (y != 0) {int z = x %y;

x=y;

y=z;

}returnx;

}voidreduction() {int tmp = gcd(this.numerator, this.denominator);this.numerator = this.numerator /tmp;this.denominator = this.denominator /tmp;

}

Fraction add(Fraction f1) {int temp =f1.denominator;

f1.denominator= this.denominator *f1.denominator;

f1.numerator= this.numerator * temp + f1.numerator * this.denominator;

f1.reduction();returnf1;

}

Fraction sub(Fraction f1) {int tmp =f1.denominator;

f1.denominator= this.denominator *f1.denominator;

f1.numerator= this.numerator * tmp - f1.numerator * this.denominator;

f1.reduction();returnf1;

}

Fraction mul(Fraction f1) {

f1.denominator= f1.denominator * this.denominator;

f1.numerator= f1.numerator * this.numerator;

f1.reduction();returnf1;

}

Fraction div(Fraction f1) {int tmp =f1.denominator;

f1.denominator= this.denominator *f1.numerator;

f1.numerator= this.numerator *tmp;

f1.reduction();returnf1;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值