【题目链接】
ybt 2058:【例3.10】简单计算器
【题目考点】
1. switch语句
2. if…else if语句
【题解代码】
解法1:switch语句
#include<bits/stdc++.h>
using namespace std;
int main()
{
double x, y;
char c;
cin >> x >> y >> c;
switch(c)
{
case '+':
cout << x + y;
break;
case '-':
cout << x - y;
break;
case '*':
cout << x * y;
break;
case '/':
if (y == 0)
cout << "Divided by zero!";
else
cout << x / y;
break;
default:
cout << "Invalid operator!";
}
return 0;
}
解法2:if…else if语句
#include<bits/stdc++.h>
using namespace std;
int main()
{
double x, y;
char c;
cin >> x >> y >> c;
if(c == '+')
cout << x + y;
else if(c == '-')
cout << x - y;
else if(c == '*')
cout << x * y;
else if(c == '/')
{
if (y == 0)
cout << "Divided by zero!";
else
cout << x / y;
}
else
cout << "Invalid operator!";
return 0;
}