📜  使用 C++ 中的类的计算器

📅  最后修改于: 2022-05-13 01:55:28.711000             🧑  作者: Mango

使用 C++ 中的类的计算器

使用类的概念在 C++ 中实现计算器。

职能:

  1. 两个数相加。
  2. 两个数字之间的差异。
  3. 两个数的乘积。
  4. 两个数的除法。

方法:

  1. 为两个数值声明局部变量 a、b。
  2. 输入选择。
  3. 接受两个数字,a 和 b。
  4. do-while 跳转到用户选择的运算符。
  5. 显示运行结果。
  6. 出口

例子:

下面是上述方法的C++程序实现——

C++
// C++ program to implement
// the above approach
#include 
#include 
using namespace std;
 
// Class calculator
class Calculator
{
   float a, b;
public:
   
    // Function to take input
    // from user
    void result()
    {
        cout << "Enter First Number: ";   
        cin >> a;
        cout << "Enter Second Number: ";  
        cin >> b;
    }
   
    // Function to add two numbers
    float add()
    {
        return a + b;
    }
   
    // Function to subtract two numbers
    float sub()
    {
        return a - b;
    }
   
    // Function to multiply two numbers
    float mul()
    {
        return a * b;
    }
   
    // Function to divide two numbers
    float div()
    {
        if (b == 0)
        {
            cout << "Division By Zero" <<
                     endl;
            return INFINITY;
        }
        else
        {
            return a / b;
        }
    }
};
 
// Driver code
int main()
{
    int ch;
    Calculator c;
    cout << "Enter 1 to Add 2 Numbers" <<
            "\nEnter 2 to Subtract 2 Numbers" <<
            "\nEnter 3 to Multiply 2 Numbers" <<
            "\nEnter 4 to Divide 2 Numbers" <<
            "\nEnter 0 To Exit";
         
    do
    {
        cout << "\nEnter Choice: ";
        cin >> ch;
        switch (ch)
        {
        case 1:
             
            // result function invoked
            c.result();    
             
            // add function to calculate sum
            cout << "Result: " <<
                     c.add() << endl;
            break;
        case 2:
             
            // sub function to calculate
            // difference
            c.result();
            cout << "Result: " <<
                     c.sub() << endl;
            break;
        case 3:
            c.result();
             
            // mul function to calculate product
            cout << "Result: " <<
                     c.mul() << endl;
            break;
        case 4:
            c.result();
             
            // div function to calculate division
            cout << "Result: " <<
                     c.div() << endl;
            break;
        }
         
    } while (ch >= 1 && ch <= 4);
     
    return 0;
}


输出:

两个数相加:

两个数相减:

两个数相乘:

两个数的除法: