一個簡單的計算機程式

來源:互聯網
上載者:User

前段時間寫了一個簡單的計算機程式,可以支援+-*/()和數字構成的運算式,每個運算式以分號結束,運行時向下面這樣:

 

$ ./a.out<br />(2+3)*(-2+5);<br />15.000 

有興趣的可以編譯後玩玩,原始碼如下:

#include <stdio.h><br />#include <stdlib.h><br />#define NONE -1<br />enum {NUM=256};<br />int lookahead;<br />double token_val;<br />int get_token()<br />{<br /> int t;<br /> while(1){<br /> t = getchar();<br /> if(t == ' ' || t == '/t')<br /> ;<br /> else if( t == '/n')<br /> ;<br /> else if (isdigit(t)){<br /> ungetc(t, stdin);<br /> scanf("%lf", &token_val);<br /> return NUM;<br /> }else if ( t == EOF)<br /> return t;<br /> else{<br /> token_val = NONE;<br /> return t; //operators, parenthesis etc.<br /> }<br /> }<br />}<br />void match(int type)<br />{<br /> if(lookahead == type)<br /> lookahead = get_token();<br /> else<br /> printf("syntax error/n");<br />}<br />double term();<br />double factor();<br />double expr()<br />{<br /> double left = term();<br /> while(1){<br /> if(lookahead == '+'){<br /> match('+');<br /> left += term();<br /> }else if(lookahead =='-'){<br /> match('-');<br /> left -= term();<br /> }else<br /> return left; //lookahead not for expr, return current value.<br /> }<br />}<br />double term()<br />{<br /> double left = factor();<br /> while(1){<br /> if(lookahead == '*'){<br /> match('*');<br /> left *= factor();<br /> }<br /> else if(lookahead =='/'){<br /> match('/');<br /> double right = factor();<br /> if(right)<br /> left /= right;<br /> else{<br /> printf("divided by zero!/n");<br /> exit(0);<br /> }<br /> }else<br /> return left; //lookahead not for term, return current value.</p><p> }<br />}<br />double factor()<br />{<br /> double left;<br /> if(lookahead == '('){<br /> match('(');<br /> left = expr();<br /> match(')');<br /> }else if(lookahead == NUM){<br /> left = token_val;<br /> match(NUM);<br /> }else if(lookahead == '-'){<br /> match('-');<br /> left = -factor();<br /> }<br /> else{<br /> printf("error: what's this?/n");<br /> exit(0);<br /> }<br /> return left;<br />}<br />int main()<br />{<br /> lookahead = get_token();<br /> while(lookahead != EOF) {<br /> printf("%.3lf/n", expr());<br /> match(';'); //end this expr<br /> }</p><p> return 0;<br />}<br /> 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.