首页 > 后端开发 > C++ > 正文

编写一个简单的计算器的C/C++程序

王林
发布: 2023-09-02 22:49:12
转载
889 人浏览过

编写一个简单的计算器的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学习者快速成长!