ZZ的计算器
Problem Description
ZZ自從上大學(xué)以來(lái),腦容量就是以SB計(jì)算的,這個(gè)吃貨竟然連算術(shù)運(yùn)算也不會(huì)了,可是當(dāng)今的計(jì)算機(jī)可是非常強(qiáng)大的,作為ACMer, 幾個(gè)簡(jiǎn)單的算術(shù)又算得了什么呢?可是該怎么做呢?ZZ只想算簡(jiǎn)單的加減乘除,由于大腦鈍化,ZZ連小數(shù)都沒(méi)有概念了!Input
有多組測(cè)試數(shù)據(jù),每組測(cè)試數(shù)據(jù)為一個(gè)字符串,字符串為合法的算術(shù)運(yùn)算,運(yùn)算符號(hào)只包含+、-、*、/,數(shù)據(jù)為整數(shù).Output
請(qǐng)輸出正確的結(jié)果,除數(shù)為0的時(shí)候,輸出impossible。(結(jié)果保證在長(zhǎng)整形之內(nèi))Sample Input
1+1*2 2/2+1Sample Output
3 2 1 #include<stdio.h> 2 #include<string.h> 3 #define LL long long 4 5 int main() 6 { 7 LL d[10000] , temp , cnt; 8 LL i , j; 9 char ch[200]; 10 while(gets(ch)) 11 { 12 cnt=temp=0; 13 for(j=0 ; j<strlen(ch) ; j++) 14 { 15 if(ch[j]>='0'&&ch[j]<='9') temp = temp*10+ch[j]-'0'; 16 else break; 17 } 18 d[cnt++]=temp; 19 for(i=j ; i<strlen(ch) ; i++) 20 { 21 temp=0; 22 for(j=i+1 ; ch[j]>='0'&&ch[j]<='9' ; j++) temp = temp*10+ch[j]-'0'; 23 if(ch[i]=='*') d[cnt-1] *= temp; 24 else if(ch[i]=='/') d[cnt-1] /= temp; 25 else if(ch[i]=='+') d[cnt++] = temp; 26 else d[cnt++] = (-1)*temp; 27 i=j-1; 28 } 29 for(i=1 ; i<cnt ; i++) d[0]+=d[i]; 30 printf("%I64d\n",d[0]); 31 } 32 return 0; 33 } 數(shù)組模擬 1 #include <stdio.h> 2 #include <string.h> 3 #include <stack> 4 using namespace std; 5 6 stack<long long> stk; 7 stack<char> op; 8 9 int main() 10 { 11 char str[100]; 12 bool bl ; 13 int len, i, j, k; 14 long long a, b; 15 while (scanf("%s",str)!=EOF) 16 { 17 bl = true; 18 while (!stk.empty()) stk.pop(); 19 while (!op.empty()) op.pop(); 20 i = 0; 21 if (str[0] == '-') i++; 22 len = strlen(str); 23 for(; i<len; i++) 24 { 25 a = str[i++]-'0'; 26 while(i < len && str[i] >='0' && str[i] <='9') 27 { 28 a *= 10; 29 a += str[i++] -'0'; 30 } 31 if (!op.empty()) 32 { 33 if (op.top() == '*') 34 { 35 b = stk.top(); 36 stk.pop(); 37 a *=b; 38 op.pop(); 39 } 40 else if (op.top() == '/') 41 { 42 b = stk.top(); 43 stk.pop(); 44 if (a == 0) 45 { 46 puts("impossible"); 47 bl = false; 48 break; 49 } 50 a = b / a; 51 op.pop(); 52 } 53 } 54 stk.push(a); 55 if (i < len) op.push(str[i]); 56 } 57 if (!bl) continue; 58 long long sum=0; 59 while (!op.empty()) 60 { 61 a = stk.top(); 62 stk.pop(); 63 if (op.top() == '+') 64 { 65 sum += a; 66 op.pop(); 67 } 68 else 69 { 70 sum -= a; 71 op.pop(); 72 } 73 } 74 75 if (str[0] == '-') sum -= stk.top(); 76 else sum += stk.top(); 77 printf("%I64d\n", sum); 78 79 } 80 return 0; 81 } 兩個(gè)棧模擬?
轉(zhuǎn)載于:https://www.cnblogs.com/contestant/p/3209633.html
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來(lái)咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
- 上一篇: 试管移植后可以吃苹果吗?
- 下一篇: 如何从 Datagrid 中获得单元格的