21xrx.com
2024-09-17 04:13:41 Tuesday
登录
文章检索 我的文章 写文章
C++编写简易计算器程序
2023-07-12 15:02:10 深夜i     --     --
C++ 计算器程序 简易

计算是我们日常生活中经常需要做的事情,而计算器就是一种方便快捷的工具。如果我们能够自己编写一个简易的计算器程序,那么不仅可以提升自己的编程能力,还能在某些场合带来实际便利。本文将介绍如何用C++编写一个简单的计算器程序。

首先,我们需要定义程序的界面。这里我们决定采用和Windows计算器类似的界面。具体来说,我们需要一个大的文本框用于显示结果,以及若干个数字按钮和运算符按钮。

接下来,我们需要考虑程序的逻辑。当用户点击数字按钮时,程序应该将这个数字添加到当前的操作数中。当用户点击运算符按钮时,程序应该将当前的操作数和上一个操作数进行运算,并将结果显示在文本框中。为了实现这一逻辑,我们需要使用一些变量来保存当前的操作数和运算符,以及一些函数来实现运算。

下面是程序的具体实现:


#include <iostream>

#include <string>

using namespace std;

double calculate(double operand1, double operand2, char operation) {

  switch (operation) {

    case '+': return operand1 + operand2;

    case '-': return operand1 - operand2;

    case '*': return operand1 * operand2;

    case '/': return operand1 / operand2;

    default: return 0;

  }

}

int main() {

  double operand1 = 0;

  double operand2 = 0;

  char operation = 0;

  bool is_operand1 = true; // 判断当前输入的数字是第一个操作数还是第二个操作数

  string input = "";

  while (true) {

    cout << "请输入数字或运算符:" << endl;

    getline(cin, input);

    if (input == "+" || input == "-" || input == "*" || input == "/") {

      if (is_operand1)

        is_operand1 = false;

       else {

        operand1 = calculate(operand1, operand2, operation);

      }

      operation = input[0];

    } else if (input == "=") {

      operand1 = calculate(operand1, operand2, operation);

      cout << "结果是:" << operand1 << endl;

      operand2 = 0;

      is_operand1 = true;

    } else {

      double num = stod(input);

      if (is_operand1)

        operand1 = num;

       else

        operand2 = num;

      

    }

  }

  return 0;

}

通过运行程序,我们可以看到一个基本的计算器界面,而且我们可以进行基本的四则运算。

当然,这个程序还有很多可以改进的地方。比如,我们可以增加一些函数按钮,如sin、cos等。我们也可以考虑增加一些功能,如对于除数为零的情况进行特殊处理。总之,这个计算器程序只是一个演示,我们可以根据实际需要进行改进和扩展。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复