hdu 1237(簡單計數器)

來源:互聯網
上載者:User

題意:輸入一個算術運算式,求值(數字為整數,但結果不一定是整數,不存在不合法的輸入)。

題目連結:http://acm.hdu.edu.cn/showproblem.php?pid=1237

——>>這是中綴運算式的運算。開兩個棧,一個用來存運算元,一個用來存運算子。定義3個層級,# 的層級最低,+ 和 - 的層級相同且高於 #,* 和 / 的層級相同且高於 + 和 - ,先往運算子棧放入一個 # ,運算式最後也加一個 #,讀運算式,若讀到數字,則以數字類型輸入,直接放入運算元棧,若讀到的是運算子,則比較讀到的運算子與運算子棧頂符號的層級,若比棧頂的高,則入棧,否則,從數棧取兩個運算元進行運算子棧頂元素的運算,再把結果壓入數棧,剛剛讀到的運算子再與現在運算子棧頂元素的層級進行比較……最後數剩下的一個元素,就是結果。

代碼如下:

/* * 1237_5.cpp * *  Created on: 2013年8月7日 *      Author: Administrator *      就算成為不了章澤天的男朋友,也要成為她的校友。。。。 *      fighting!!!!! */#include <iostream>#include <stack>#include <cstdio>using namespace std;int priority(char c) {if (c == '#') {return 1;} else if (c == '+' || c == '-') {return 2;} else if (c == '*' || c == '/') {return 3;}return -1;}double cal(double a, double b, char c) {if (c == '+') {return a + b;} else if (c == '-') {return a - b;} else if (c == '*') {return a * b;} else if (c == '/') {return a / b;}return -1;}int main() {char s[210];while (cin.getline(s, sizeof(s))) {if (strcmp(s, "0") == 0) {break;}int len = strlen(s);s[len++] = ' ';s[len++] = '#';s[len] = 0;stack<double> digit;stack<char> f;f.push('#');for (int i = 0; i < len; ++i) {if (s[i] == ' ') {continue;}if (isdigit(s[i])) {double temp;sscanf(s + i, "%lf", &temp);digit.push(temp);while (isdigit(s[i + 1])) {i++;}} else {bool ok = 1;while (ok) {if (priority(s[i]) > priority(f.top())) {f.push(s[i]);ok = 0;} else {if (s[i] == '#' && f.top() == '#') {break;}double b = digit.top();digit.pop();double a = digit.top();digit.pop();char c = f.top();f.pop();double ret = cal(a, b, c);digit.push(ret);}}}}double result = digit.top();printf("%.2lf\n", result);while (!f.empty()) {f.pop();}while (!digit.empty()) {digit.pop();}}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.