使用switch...case语句创建简单的C++加减乘除计算器程序
让我们来看一个用C++创建简单计算器的程序,包含加、减、乘、除运算。
示例
#include <iostream>
using namespace std;
void calculator(int a, int b, char op) {
switch (op) {
case '+': {
cout<<"Sum of "<<a<<" and "<<b<<" is "<<a+b<<endl;
break;
}
case '-': {
cout<<"Difference of "<<a<<" and "<<b<<" is "<<a-b<<endl;
break;
}
case '*': {
cout<<"Product of "<<a<<" and "<<b<<" is "<<a*b<<endl;
break;
}
case '/': {
cout<<"Division of "<<a<<" and "<<b<<" is "<<a/b<<endl;
break;
}
default:
cout<<"Invalid Input"<<endl;
}
}
int main() {
calculator(5,4,'+');
calculator(10,3,'-');
calculator(3,2,'*');
calculator(20,5,'/');
calculator(5,2,'?');
return 0;
}输出
Sum of 5 and 4 is 9 Difference of 10 and 3 is 7 Product of 3 and 2 is 6 Division of 20 and 5 is 4 Invalid Input
在上面的程序中,使用了calculator函数来对两个数字进行加、减、乘、除运算。这是使用switch case语句实现的。该函数接受三个参数:两个要进行运算的数字和要执行的运算。如下所示:
void calculator(int a, int b, char op)
switch case语句中有四个case和一个default case。第一个case用于执行加法运算。两个数字相加,并显示它们的和。使用以下代码片段:
case '+': {
cout<<"Sum of "<<a<<" and "<<b<<" is "<<a+b<<endl;
break;
}第二个case用于执行减法运算。两个数字相减,并显示它们的差。使用以下代码片段:
case '-': {
cout<<"Difference of "<<a<<" and "<<b<<" is "<<a-b<<endl;
break;
}第三个case用于执行乘法运算。两个数字相乘,并显示它们的积。使用以下代码片段:
case '*': {
cout<<"Product of "<<a<<" and "<<b<<" is "<<a*b<<endl;
break;
}第四个case用于执行除法运算。两个数字相除,并显示它们的商。使用以下代码片段:
case '/': {
cout<<"Division of "<<a<<" and "<<b<<" is "<<a/b<<endl;
break;
}default case用于处理无效的运算符。使用以下代码片段:
default: cout<<"Invalid Input"<<endl;
calculator()函数在main()函数中被调用,用于执行不同的运算和使用不同的操作数。这由以下代码片段演示:
calculator(5,4,'+'); calculator(10,3,'-'); calculator(3,2,'*'); calculator(20,5,'/'); calculator(5,2,'?');
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP