跳到正文

科技·工程

计算器(windows.h)

违规用户名2090093约 23 分钟
原文
文章信息与版本

文章信息

发布
2026年9月13日
收录
2026年9月13日
更新
2026年9月22日
篇幅
约 23 分钟

版本

  1. v1当前
C++
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <iomanip>
#include <cmath>
#include <conio.h> 
#include <windows.h>
using namespace std;

const int WIDTH = 52;
const int HEIGHT = 24;
const char* TITLE = "C++ CONSOLE CALCULATOR";
const char* VERSION = "v2.0";

void gotoxy(int x, int y) {
    COORD c = {(short)x, (short)y};
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), c);
}

void setColor(int color) {
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color);
}

void hideCursor() {
    CONSOLE_CURSOR_INFO cci = {1, 0};
    SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cci);
}

void bootAnimation() {
    system("cls");
    hideCursor();
    setColor(10);
    cout << "\n\n";
    string msg = "  [SYSTEM] Initializing Console Calculator...";
    for (size_t i = 0; i < msg.size(); i++) {
        cout << msg[i];
        Sleep(30);
    }
    cout << "\n";
    Sleep(200);
    setColor(14);
    cout << "  [SYSTEM] Loading modules...\n";
    Sleep(300);
    setColor(11);
    cout << "  [OK] Math Engine\n"; Sleep(150);
    cout << "  [OK] Display Driver\n"; Sleep(150);
    cout << "  [OK] Input Handler\n"; Sleep(150);
    cout << "  [OK] History Manager\n"; Sleep(150);
    setColor(10);
    cout << "  [SYSTEM] Ready! Launching in 1s...\n";
    Sleep(800);
    system("cls");
}

void drawBorder() {
    setColor(11);
    for (int i = 0; i < WIDTH; i++) {
        gotoxy(i, 0); cout << "=";
        gotoxy(i, HEIGHT - 1); cout << "=";
    }
    for (int i = 0; i < HEIGHT; i++) {
        gotoxy(0, i); cout << "|";
        gotoxy(WIDTH - 1, i); cout << "|";
    }
    gotoxy(0, 0); cout << "/";
    gotoxy(WIDTH - 1, 0); cout << "\\";
    gotoxy(0, HEIGHT - 1); cout << "\\";
    gotoxy(WIDTH - 1, HEIGHT - 1); cout << "/";

    int titleLen = (int)strlen(TITLE);
    int tx = (WIDTH - titleLen) / 2;
    setColor(14); gotoxy(tx, 0); cout << " " << TITLE << " ";
    int verLen = (int)strlen(VERSION);
    setColor(8); gotoxy(WIDTH - 1 - verLen, 0); cout << VERSION;
    setColor(11);
}

void drawPanel(int x, int y, int w, int h, const string& label) {
    setColor(8);
    for (int i = 1; i <= w; i++) {
        gotoxy(x + i, y); cout << "-";
        gotoxy(x + i, y + h - 1); cout << "-";
    }
    for (int i = 1; i <= h - 2; i++) {
        gotoxy(x, y + i); cout << "|";
        gotoxy(x + w, y + i); cout << "|";
    }
    gotoxy(x, y); cout << "+";
    gotoxy(x + w, y); cout << "+";
    gotoxy(x, y + h - 1); cout << "+";
    gotoxy(x + w, y + h - 1); cout << "+";
    if (!label.empty()) {
        int lx = x + (w - (int)label.size()) / 2;
        setColor(7); gotoxy(lx, y); cout << label;
        setColor(8);
    }
}

vector<string> getKeys() {
    vector<string> keys;
    keys.push_back("7"); keys.push_back("8"); keys.push_back("9");
    keys.push_back("/"); keys.push_back("C");
    keys.push_back("4"); keys.push_back("5"); keys.push_back("6");
    keys.push_back("*"); keys.push_back("(");
    keys.push_back("1"); keys.push_back("2"); keys.push_back("3");
    keys.push_back("-"); keys.push_back(")");
    keys.push_back("0"); keys.push_back("."); keys.push_back("=");
    keys.push_back("+"); keys.push_back("DEL");
    return keys;
}

void drawKeypad() {
    drawPanel(1, 1, 50, 5, " DISPLAY ");
    drawPanel(1, 7, 50, 16, " KEYPAD ");
    vector<string> keys = getKeys();
    int kx = 3, ky = 9;
    for (int i = 0; i < 20; i++) {
        int cx = kx + (i % 5) * 10;
        int cy = ky + (i / 5) * 3;
        setColor(8);
        gotoxy(cx, cy); cout << "+--------+";
        gotoxy(cx, cy + 1); cout << "|        |";
        gotoxy(cx, cy + 2); cout << "+--------+";
        setColor(15);
        gotoxy(cx + 4, cy + 1); cout << keys[i];
    }
}

void highlightKey(int idx) {
    vector<string> keys = getKeys();
    int kx = 3, ky = 9;
    int cx = kx + (idx % 5) * 10;
    int cy = ky + (idx / 5) * 3;
    setColor(14);
    gotoxy(cx, cy); cout << "+--------+";
    gotoxy(cx, cy + 1); cout << "|        |";
    gotoxy(cx, cy + 2); cout << "+--------+";
    gotoxy(cx + 4, cy + 1); cout << keys[idx];
    Sleep(80);
    setColor(8);
    gotoxy(cx, cy); cout << "+--------+";
    gotoxy(cx, cy + 1); cout << "|        |";
    gotoxy(cx, cy + 2); cout << "+--------+";
    setColor(15);
    gotoxy(cx + 4, cy + 1); cout << keys[idx];
}

int getKeyIndex(char c) {
    string keys = "789/C456*(123-)0.=+D";
    for (int i = 0; i < 20; i++) {
        if (keys[i] == c) return i;
    }
    return -1;
}

int getPrecedence(char op) {
    if (op == '+' || op == '-') return 1;
    if (op == '*' || op == '/') return 2;
    return 0;
}

void applyOp(vector<double>& nums, vector<char>& ops) {
    double b = nums.back(); nums.pop_back();
    double a = nums.back(); nums.pop_back();
    char op = ops.back(); ops.pop_back();
    if (op == '+') nums.push_back(a + b);
    else if (op == '-') nums.push_back(a - b);
    else if (op == '*') nums.push_back(a * b);
    else if (op == '/') {
        if (fabs(b) < 1e-9) { nums.push_back(1e18); return; }
        nums.push_back(a / b);
    }
}

string evaluate(const string& expr) {
    if (expr.empty()) return "";
    for (size_t i = 0; i < expr.size(); i++) {
        char c = expr[i];
        if (!(c >= '0' && c <= '9') && c != '+' && c != '-' &&
            c != '*' && c != '/' && c != '.' && c != '(' && c != ')')
            return "ERROR";
    }
    char last = expr[expr.size() - 1];
    if (last == '+' || last == '-' || last == '*' || last == '/')
        return "ERROR";

    vector<double> nums;
    vector<char> ops;
    istringstream iss(expr);
    char c;
    while (iss >> c) {
        if ((c >= '0' && c <= '9') || c == '.') {
            iss.putback(c);
            double val; iss >> val;
            nums.push_back(val);
        } else if (c == '(') {
            ops.push_back(c);
        } else if (c == ')') {
            while (!ops.empty() && ops.back() != '(') applyOp(nums, ops);
            if (!ops.empty()) ops.pop_back();
        } else {
            while (!ops.empty() && ops.back() != '(' &&
                   getPrecedence(ops.back()) >= getPrecedence(c))
                applyOp(nums, ops);
            ops.push_back(c);
        }
    }
    while (!ops.empty()) applyOp(nums, ops);
    if (nums.empty()) return "ERROR";
    double res = nums.back();
    if (fabs(res) > 1e17) return "DIV/0!";
    ostringstream oss;
    oss << fixed << setprecision(6) << res;
    string s = oss.str();
    size_t dot = s.find('.');
    if (dot != string::npos) {
        size_t lastNonZero = s.find_last_not_of('0');
        if (lastNonZero != string::npos && s[lastNonZero] == '.') lastNonZero--;
        if (lastNonZero != string::npos) s = s.substr(0, lastNonZero + 1);
    }
    return s;
}

string repeatChar(char c, int n) {
    string s = "";
    for (int i = 0; i < n; i++) s += c;
    return s;
}

int main() {
    bootAnimation();
    system("cls");
    drawBorder();
    drawKeypad();

    string expr = "";
    string lastResult = "";
    vector<string> history;
    int histIdx = 0;

    while (true) {
        // 刷新显示
        setColor(10);
        gotoxy(3, 3); cout << repeatChar(' ', 46);
        string show = expr;
        if ((int)show.size() > 44) show = "..." + show.substr(show.size() - 41);
        gotoxy(3 + (46 - (int)show.size()) / 2, 3);
        cout << show;

        setColor(14);
        gotoxy(3, 4); cout << repeatChar(' ', 46);
        if (!lastResult.empty()) {
            string r = "= " + lastResult;
            gotoxy(3 + (46 - (int)r.size()) / 2, 4);
            cout << r;
        }

        setColor(8);
        gotoxy(2, 20); cout << repeatChar(' ', 48);
        if (!history.empty()) {
            string h = history[histIdx];
            if ((int)h.size() > 46) h = h.substr(0, 43) + "...";
            gotoxy(3 + (46 - (int)h.size()) / 2, 20);
            cout << h;
        }

        setColor(7);
        gotoxy(2, HEIGHT + 1);
        cout << "Keys: 0-9 . + - * / ( ) | Enter=Calc | Backspace=Del | C=Clear | Esc=Quit";
        gotoxy(2, HEIGHT + 2);
        cout << "Up/Down: History  |  Space: Copy result to input";

        if (_kbhit()) {
            char key = _getch();
            if (key == -32) {
                key = _getch();
                if (key == 72 && !history.empty()) {
                    histIdx = (histIdx + 1) % (int)history.size();
                } else if (key == 80 && !history.empty()) {
                    histIdx = (histIdx - 1 + (int)history.size()) % (int)history.size();
                }
                continue;
            }

            int ki = -1;
            if (key >= '0' && key <= '9') ki = getKeyIndex(key);
            else if (key == '.') ki = 16;
            else if (key == '+') ki = 18;
            else if (key == '-') ki = 13;
            else if (key == '*') ki = 8;
            else if (key == '/') ki = 3;
            else if (key == '(') ki = 9;
            else if (key == ')') ki = 14;
            else if (key == '\r') ki = 17;
            else if (key == 8) ki = 19;
            else if (key == 'c' || key == 'C') ki = 4;
            else if (key == 27) {
                setColor(12);
                gotoxy(WIDTH / 2 - 8, HEIGHT / 2);
                cout << "  Goodbye!  ";
                Sleep(600);
                setColor(7);
                gotoxy(0, HEIGHT + 3);
                return 0;
            } else if (key == ' ') {
                if (!lastResult.empty() && lastResult != "ERROR" && lastResult != "DIV/0!") {
                    expr = lastResult;
                    lastResult = "";
                }
                continue;
            }

            if (ki >= 0) highlightKey(ki);

            if (key >= '0' && key <= '9') {
                expr += key;
            } else if (key == '.') {
                if (!expr.empty() && !(expr[expr.size()-1] >= '0' && expr[expr.size()-1] <= '9')) continue;
                expr += '.';
            } else if (key == '+' || key == '-' || key == '*' || key == '/') {
                if (expr.empty() && key != '-') continue;
                if (!expr.empty()) {
                    char lb = expr[expr.size()-1];
                    if (!((lb >= '0' && lb <= '9') || lb == ')')) continue;
                }
                expr += key;
            } else if (key == '(') {
                if (!expr.empty() && (expr[expr.size()-1] >= '0' && expr[expr.size()-1] <= '9')) continue;
                expr += '(';
            } else if (key == ')') {
                if (expr.empty() || !(expr[expr.size()-1] >= '0' && expr[expr.size()-1] <= '9')) continue;
                expr += ')';
            } else if (key == '\r') {
                if (!expr.empty()) {
                    lastResult = evaluate(expr);
                    string histEntry = expr + " = " + lastResult;
                    history.push_back(histEntry);
                    histIdx = (int)history.size() - 1;
                    expr = "";
                }
            } else if (key == 8) {
                if (!expr.empty()) {
                    expr.erase(expr.size() - 1);
                }
            } else if (key == 'c' || key == 'C') {
                expr = "";
                lastResult = "";
            }
        }
        Sleep(10);
    }
    return 0;
}
原文