C/C++ 程式製作一個簡單的計算器?


一個簡單的計算器是一個可以執行一些基本操作(例如“+”、“-”、“*”、“/”)的計算器。一個計算器能夠快速地執行基本操作。我們將使用 switch 語句來製作一個計算器。

示例

Operator − ‘+’ => 34 + 324 = 358
Operator − ‘-’ => 3874 - 324 = 3550
Operator − ‘*’ => 76 * 24 = 1824
Operator − ‘/’ => 645/5 = 129

示例程式碼

#include <iostream<
using namespace std;
int main() {
   char op = '+';
   float a = 63, b= 7;
   // cout << "Enter operator either + or - or * or /: ";
   // cin >> op;
   cout<<"The operator is "<<op<<endl;
   // cout << "Enter two operands: ";
   // cin>> a >> b;
   cout<<"a = "<<a<<" b = "<<b<<endl;
   switch(op) {
      case '+':
         cout <<"Sum of"<<a<<"and"<<b<<"is"<< a+b;
      break;
      case '-':
         cout <<"Difference of"<<a<<"and"<<b<<"is"<<a-b;
      break;
      case '*':
         cout <<"Product of"<<a<<"and"<<b<<"is"<<a*b;
      break;
      case '/':
         cout <<"Division of"<<a<<"and"<<b<<"is"<<a/b;
      break;
      default:
         // If the operator is other than +, -, * or /, error message is shown
         cout << "Error! operator is not correct";
      break;
   }
   return 0;
}

輸出

The operator is +
a = 63 b = 7
Sum of63 and 7 is 70

更新日期: 2019 年 7 月 30 日

892 次瀏覽

開啟你的職業生涯

完成課程並獲得認證

開始
廣告