题解 | #简单计算器#
简单计算器
https://www.nowcoder.com/practice/b8f770674ba7468bb0a0efcc2aa3a239
C++ 写的,有够麻烦的。
#include <iostream> using namespace std; # include <cmath> # include <iomanip> int main() { string a; string x1, x2; char sym; cin >> a; int n = a.size(); int i = 0; bool f = (a[3] == '+'); while (((int)(a[i] - 48) >= 0 && (int)(a[i] - 48) <= 9) || a[i]=='.') { x1 = x1 + a[i]; ++i; } int x1_n = i; sym = a[i]; ++i; while (i < n) { x2 = x2 + a[i]; ++i; } int x2_n = n - x1_n - 1; int j = 0; double x1_s = 0; while (j < x1_n && x1[j] != '.') { x1_s = pow(10, j) * x1_s + (x1[j] - 48); j++; } if (x1[j] == '.') { j++; int p = j; while (j < x1_n) { x1_s = x1_s + pow(10, p - 1 - j) * (x1[j] - 48); j++; } } j = 0; double x2_s = 0; while (j < x2_n && x2[j] != '.') { x2_s = pow(10, j) * x2_s + (x2[j] - 48); j++; } if (x2[j] == '.') { j++; int p = j; while (j < x2_n) { x2_s = x2_s + pow(10, p - 1 - j) * (x2[j] - 48); j++; } } switch (sym) { case '+': cout << fixed << setprecision(4) << x1_s << "+" << fixed << setprecision(4) << x2_s << "=" << fixed << setprecision(4) << x1_s + x2_s; break; case '-': cout << fixed << setprecision(4) << x1_s << "-" << fixed << setprecision(4) << x2_s << "=" << fixed << setprecision(4) << x1_s - x2_s; break; case '*': cout << fixed << setprecision(4) << x1_s << "*" << fixed << setprecision(4) << x2_s << "=" << fixed << setprecision(4) << x1_s * x2_s; break; case '/': { if (x2_s == 0) cout << "Wrong!Division by zero!"; else cout << fixed << setprecision(4) << x1_s << "/" << fixed << setprecision(4) << x2_s << "=" << fixed << setprecision(4) << x1_s / x2_s; break; break; } default: cout << "Invalid operation!"; break; } } // 64 位输出请用 printf("%lld")
C++题解 文章被收录于专栏
记录在牛客网用C++刷题的题解思路