题解 | #计算器的改良# C++
计算器的改良
https://ac.nowcoder.com/acm/problem/16749
#include <iostream> #include <cstdio> #include <cmath> #include <string> using namespace std; int main(){ // x是系数;v是值;等号左边equal为1,右边为-1;sign记录符号位;total记录系数或值的数字; int x = 0, v = 0, equal = 1, sign = 1, total = 0; // t记录未知数 char c, t; while (cin >> c) { // 遇到+号,值移到右边,符号位记为1,total归0 if (c == '+') { v -= total * sign * equal; sign = 1; total = 0; // 遇到-号,值移到右边,符号位记为-1,total归0 }else if (c == '-') { v -= total * sign * equal; sign = -1; total = 0; // 遇到=号,值移到右边,符号位记为1,total归0,equal记为-1 }else if (c == '=') { v -= total * sign * equal; sign = 1; equal = -1; total = 0; // 如果total为0系数为1,t记录未知数,将系数移项至左边,total归0 }else if (isalpha(c)) { if (total == 0) x += 1; t = c; x += total * sign * equal; total = 0; // 记录系数或值 }else { total = total * 10 + (c - '0'); } } // 计算最后一个值 v -= total * sign * equal; printf("%c=%.3f\n", t, (double)v/x); return 0; }