首頁 > 後端開發 > C++ > 主體

寫一個簡單的計算器的C/C++程序

王林
發布: 2023-09-02 22:49:12
轉載
890 人瀏覽過

寫一個簡單的計算器的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 = &#39;+&#39;;
   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 &#39;+&#39;:
         cout <<"Sum of"<<a<<"and"<<b<<"is"<< a+b;
      break;
      case &#39;-&#39;:
         cout <<"Difference of"<<a<<"and"<<b<<"is"<<a-b;
      break;
      case &#39;*&#39;:
         cout <<"Product of"<<a<<"and"<<b<<"is"<<a*b;
      break;
      case &#39;/&#39;:
         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
登入後複製

以上是寫一個簡單的計算器的C/C++程序的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!