Simple Calculator
Time limit:2000/1000 MS (java/others) Memory limit:65536/32768 K (java/others)
Total submission (s): 14833 Accepted Submission (s): 5050
problem Descriptionreads a non-negative integer that contains only a +,-, *,/, evaluates the expression, and computes the value of the expression.
InputThe test input contains several test cases, one row per test case, and no more than 200 characters per line, separated by a space between integers and operators. There is no illegal expression. When only 0 o'clock input is completed in a row, the corresponding result is not output.
OutputOutput 1 rows For each test case, that is, the value of the expression, exactly 2 digits after the decimal point.
Sample Input
1 + 24 + 2 * 5-7/110
Sample Output
3.0013.36
Just use the stack, C code is as follows:
#include <cstdio> #include <cstring>double a[210];int main () {int i,sign,count,j;double Sum;char c;while (1) {Sign=1;i=0;memset (a,0,sizeof (a)); scanf ("%lf", &a[0]); while (GetChar ()! = ' \ n ') {sign=0;scanf ("%c%d", &c, &count); if (c== ' + ') a[++i]=count;else if (c== '-') a[++i]=-count;else if (c== ' * ') a[i]=a[i]*count; else if (c== '/') a[i]=a[i]/(count* (1.0));} if (sign) break;sum=0;for (j=0;j<=i;j++) sum+=a[j];p rintf ("%0.2lf\n", sum);} return 0;}
C + + Stl--stack solution:
#include <cstdio> #include <stack>using namespace Std;int main () {int i,sign,j;double Sum,num;char c;while (1 {sign=1;stack<double>count;scanf ("%lf", &num); Count.push (num); while (GetChar ()! = ' \ n ') {sign=0;scanf ("% C%lf ", &c,&num), if (c== ' + ') Count.push (num), else if (c== '-') Count.push (-num); else if (c== ' * ') { Double X=count.top (); X=x*num;count.pop (); Count.push (x);} Else{double x=count.top (); X=x/num;count.pop (); Count.push (x);}} if (sign)
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Hdoj 1237 Simple calculator (stack)