信息学奥赛一本通 1057:简单计算器 | OpenJudge NOI 1.4 19:简单计算器

【题目链接】

ybt 1057:简单计算器
OpenJudge NOI 1.4 19:简单计算器

【题目考点】

1. switch语句
2. if…else if…else语句
3. 函数

【题解代码】

解法1:使用switch语句
#include<bits/stdc++.h>
using namespace std; 
int main()
{
    int x, y;//声明两个整型变量,表示参与运算的数字
    char c;//声明字符型变量,表示运算符
    cin >> x >> y >> c;//输入变量
    switch(c)//switch选择语句,看变量c与哪个case后面的常量相等
    {
        case '+'://如果c是'+'
            cout << x + y;//输出x+y的结果
            break;
        case '-'://如果c是'-'
            cout << x - y;//输出x-y的结果
            break;
        case '*'://如果c是'*'
            cout << x * y;//输出x*y的结果
            break;
        case '/'://如果c是'/'
            if (y == 0)//如果除数是0
                cout << "Divided by zero!";//输出:除0,这是非法运算
            else
                cout << x / y;//输出x/y的结果
            break;
        default://如果运算符不是 + - * /
            cout << "Invalid operator!";//输出"非法运算符"
    }
    return 0;
}
解法2:使用if…else if…else语句
#include<bits/stdc++.h>
using namespace std; 
int main()
{
    int 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)//如果除数是0
            cout << "Divided by zero!";//输出:除0,这是非法运算
        else
            cout << x / y;
    }
    else
        cout << "Invalid operator!";//输出"非法运算符"
    return 0;
}
解法3:写函数
#include<bits/stdc++.h>
using namespace std;
int calc(int a, int b, char c)//已知a,b,c合法 
{
	switch(c)
	{
		case '+':
			return a+b;
		case '-':
			return a-b;
		case '*':
			return a*b;
		case '/':
			return a/b;
	}
}
int main()
{
	int a, b;
	char c;
	cin >> a >> b >> c;
	if(c != '+' && c != '-' && c != '*' && c != '/')
		cout << "Invalid operator!";
	else if(c == '/' && b == 0)
		cout << "Divided by zero!";
	else
		cout << calc(a, b, c);
	return 0;
}