使用 C++ 中的类的计算器
使用类的概念在 C++ 中实现计算器。
职能:
- 两个数相加。
- 两个数字之间的差异。
- 两个数的乘积。
- 两个数的除法。
方法:
- 为两个数值声明局部变量 a、b。
- 输入选择。
- 接受两个数字,a 和 b。
- do-while 跳转到用户选择的运算符。
- 显示运行结果。
- 出口
例子:
Input: a = 5, b = 10, choice = 1
Output: Sum is 15
Input: a = 10, b = 4, choice = 3
Output: Product is 40
下面是上述方法的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;
}
输出:
两个数相加:
两个数相减:
两个数相乘:
两个数的除法: