口算练习题
题目描述
王老师正在教简单算术运算。细心的王老师收集了i道学生经常做错的口算题,并且想整理编写成一份练习。 编排这些题目是一件繁琐的事情,为此他想用计算机程序来提高工作效率。王老师希望尽量减少输入的工作量,比如 5+8 \texttt{5+8} 5+8 的算式最好只要输入 5 \texttt 5 5 和 8 \texttt 8 8,输出的结果要尽量详细以方便后期排版的使用,比如对于上述输入进行处理后输出 5+8=13 \texttt{5+8=13} 5+8=13 以及该算式的总长度 6 6 6。王老师把这个光荣的任务交给你,请你帮他编程实现以上功能。
输入格式
第一行为数值 i i i
接着的 i i i 行为需要输入的算式,每行可能有三个数据或两个数据。
若该行为三个数据则第一个数据表示运算类型, a \texttt a a 表示加法运算, b \texttt b b 表示减法运算, c \texttt c c 表示乘法运算,接着的两个数据表示参加运算的运算数。
若该行为两个数据,则表示本题的运算类型与上一题的运算类型相同,而这两个数据为运算数。
输出格式
输出 2 × i 2\times i 2×i 行。对于每个输入的算式,输出完整的运算式及结果,第二行输出该运算式的总长度
样例 #1
样例输入 #1
4
a 64 46
275 125
c 11 99
b 46 64
样例输出 #1
64+46=110
9
275+125=400
11
11*99=1089
10
46-64=-18
9
提示
数据规模与约定
对于 50 % 50\% 50% 的数据,输入的算式都有三个数据,第一个算式一定有三个数据。
对于所有数据, 0 < i ≤ 50 0<i\leq 50 0<i≤50,运算数为非负整数且小于 10000 10000 10000。
题解
在 C++ 中,当使用输入操作符 >> 从输入流中读取数据时,如果输入的数据类型与预期的不匹配,或者输入流中包含无效字符,就会发生输入流错误。例如,当输入预期是一个整数,但实际输入了一个字符串时,输入流就会进入错误状态。
cin.clear() 的作用是清除输入流的错误状态,使其能够继续接受输入。它会重置输入流的错误标志位,并丢弃输入流中的错误字符,以便后续的输入操作可以正常进行。
本题解利用了cin输入流的这一特性对输入的类型进行判断,具体细节见代码
#include <iostream>
#include <string>
#include <algorithm>
#include <cmath>
using namespace std;
int n, x, y; char ch, pre;
string toString(int d) {
int t = fabs(d); string s = "";
while (t > 0) {
s += t % 10; t /= 10;
}
//特判d=0的情况
if (d == 0) {
s += '0';
}
else {
//特判d<0的情况
if (d < 0) {
s += '-';
}
reverse(s.begin(), s.end());
}
return s;
}
void printFormula(char op, int x, int y) {
string formula; int ans = 0;
if (op == '+') {
ans = x + y;
}
else if (op == '-') {
ans = x - y;
}
else if (op == '*') {
ans = x * y;
}
cout << x << op << y << '=' << ans << '\n';
formula = "";
formula += toString(x);
formula += op;
formula += toString(y);
formula += '=';
formula += toString(ans);
cout << formula.length() << '\n';
}
int main()
{
cin >> n;
for (int i = 1; i <= n; i++) {
//如果输入x的是字符
if (!(cin >> x)) {
//输入类型不匹配,必须调用cin.clear()清除错误的输入状态才能继续使用
cin.clear(); cin >> ch;
cin >> x >> y;
switch (ch) {
case 'a':
printFormula('+', x, y);
break;
case 'b':
printFormula('-', x, y);
break;
case 'c':
printFormula('*', x, y);
break;
}
pre = ch;
}
//如果输入x的是数字
else {
//输入正确,无需调用cin.clear()
ch = pre; cin >> y;
switch (ch) {
case 'a':
printFormula('+', x, y);
break;
case 'b':
printFormula('-', x, y);
break;
case 'c':
printFormula('*', x, y);
break;
}
}
}
return 0;
}