萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C# 實作 Windows 計算機完整範例

專案結構

  • WinForms 專案,單一表單 Form1。
  • 介面:一個 TextBox 顯示、數字鍵 0-9、四則運算鍵、等號、小數點、正負號、平方/開根號、C/CE 清除鍵。
  • 選單列提供「標準/科學」切換(示範用,功能未全實作)。

核心邏輯

  • 維護 currentValue、pendingValue、pendingOp 三個狀態變數。
  • 數字鍵累加至 `currentValue` 顯示字串。
  • 運算鍵按下時:若有 `pendingOp` 先執行運算,再儲存新運算子與 `pendingValue`,清空 `currentValue` 等待下一輸入。
  • 等號鍵:執行 `pendingOp` 並顯示結果,清除待定狀態。
  • C 清除全部,CE 僅清除當前輸入。

關鍵代碼片段

private double currentValue = 0, pendingValue = 0;
private string pendingOp = "";
private bool newInput = true;

private void NumberBtn_Click(object sender, EventArgs e) {
    Button btn = (Button)sender;
    if (newInput) { txtShow.Text = btn.Text; newInput = false; }
    else txtShow.Text += btn.Text;
}

private void OperatorBtn_Click(object sender, EventArgs e) {
    Button btn = (Button)sender;
    double val = double.Parse(txtShow.Text);
    if (pendingOp != "") Calculate();
    pendingValue = val;
    pendingOp = btn.Text; // + - * / sqrt sqr 等
    newInput = true;
}

private void EqualsBtn_Click(object sender, EventArgs e) {
    Calculate();
    pendingOp = "";
    newInput = true;
}

private void Calculate() {
    double val = double.Parse(txtShow.Text);
    double result = 0;
    switch (pendingOp) {
        case "+": result = pendingValue + val; break;
        case "-": result = pendingValue - val; break;
        case "*": result = pendingValue * val; break;
        case "/": result = val != 0 ? pendingValue / val : double.NaN; break;
        case "sqrt": result = Math.Sqrt(val); break;
        case "sqr": result = val * val; break;
    }
    txtShow.Text = result.ToString();
    currentValue = result;
}

完整代碼下載

原文提供完整 `Form1.cs` 含設計器生成代碼,可直接建立專案貼上運行。

copyright © 萬盛學電腦網 all rights reserved