题解 | #计算表达式#
计算表达式
https://www.nowcoder.com/practice/7b18aa6b7cc14f8eaae6b8acdebf890b
#include<iostream> #include<vector> #include<string> using namespace std; int main(){ string str; while (getline(cin, str)){ vector<float>vec; float num = 0; char Presign = '+'; int n = str.size(); for (int i = 0; i < n; i++){ if (isdigit(str[i])){ num = num * 10 + str[i] - '0'; } if (!isdigit(str[i]) || i == n - 1){ switch (Presign){ case'+': vec.push_back(num); break; case'-': vec.push_back(-num); break; case'*': vec.back() *= num; break; default: vec.back() /= num; break; } Presign = str[i]; num = 0; } } float ans = 0; for (int i = 0; i < vec.size(); i++){ ans += vec[i]; } int answer = ans; printf("%d\n", answer); } }