把「操作符→运算」做成 4 键分派,合法性即键是否存在;除零单独判,C++ 的 `/` 是向零取整。
OJ: roj
题目 ID: 1057
难度:入门
标签:入门模拟分派表python
创建: 2026-09-29 16:35
更新: 2026-10-04 23:43
题目描述
实现只支持 + - * / 的整数计算器,读入两个整数 Invalid operator!;除法且 Divided by zero!;否则输出 int 内)。输入一行 a b op,输出一行结果。样例 1 2 + → 3。
思路
读入 Invalid operator!;再判除零(仅当 op == '/' && b == 0),最后按 + - * / 分支做对应整数运算,C++ 的 / 天然向零取整。
参考代码
Python 版:
python
#!/usr/bin/env python3
# Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
# rbook: -> https://rbook.roj.ac.cn https://rbook2.roj.ac.cn
# rainboy的学习导航网站: https://idx.roj.ac.cn
# create_at: 2026-09-29 16:35
# update_at: 2026-09-29 16:44
import operator
import sys
INVALID = "Invalid operator!" # 操作符不在四则运算内
DIV_ZERO = "Divided by zero!" # 除数为 0
def trunc_div(a: int, b: int) -> int:
"""C++ 风格的整除:向零取整(Python 的 // 向下取整,异号时需要修正)。"""
q = abs(a) // abs(b)
return q if (a < 0) == (b < 0) else -q
# 操作符分发表:键是题面的操作符字符,值是它的二元运算实现。
# "操作符是否合法"即"字符是否在表里",校验与求值共用同一份数据。
OPS = {
b'+': operator.add,
b'-': operator.sub,
b'*': operator.mul,
b'/': trunc_div,
}
def evaluate(a: int, b: int, op: bytes) -> str:
"""算出这一行该输出的内容:非法操作符优先,其次是除零,否则查表求值。"""
if op not in OPS:
return INVALID
if op == b'/' and b == 0: # 除零只在合法除法下才算,5 0 + 仍是普通加法
return DIV_ZERO
return str(OPS[op](a, b))
def solve() -> None:
x, y, op = sys.stdin.buffer.read().split() # 两个操作数 + 一个操作符
print(evaluate(int(x), int(y), op))
if __name__ == "__main__":
solve()C++ 版(同一算法):
cpp
/**
* Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
* rbook: -> https://rbook.roj.ac.cn https://rbook2.roj.ac.cn
* rainboy的学习导航网站: https://idx.roj.ac.cn
* create_at: 2026-10-04 23:43
* update_at: 2026-10-04 23:43
*/
#include <iostream>
using namespace std;
typedef long long ll;
int main() {
// 读入两个整数和一个操作符
ll a, b;
char op;
if (!(cin >> a >> b >> op)) return 0;
// 先判断操作符是否合法,非法优先于除零报错
bool valid = (op == '+' || op == '-' || op == '*' || op == '/');
if (!valid) {
cout << "Invalid operator!" << endl;
return 0;
}
// 合法操作符下,再判断除数为零(只对除法生效)
if (op == '/' && b == 0) {
cout << "Divided by zero!" << endl;
return 0;
}
// 按操作符分支计算;C++ / 是向零取整
if (op == '+') cout << a + b << endl;
else if (op == '-') cout << a - b << endl;
else if (op == '*') cout << a * b << endl;
else cout << a / b << endl; // op == '/'
return 0;
}