洛谷 P1957: 口算练习题
第三篇 CSDN!
写程序讲究大道至简!
这道题除了考点字符串,就是纯模拟!
- 每次先读入两个字符串,如果第一个字符串不是 a , b \text{a},\text{b} a,b 或 c \text{c} c 时,那么根据上一次的操作类型(可以拿变量记录) 作为本次操作类型。
- 否则,再读入第三个数,将上一次的操作类型变为这次的操作类型,判断操作类型,不同的操作类型按不同的输出就行了。
但(你说你不想在这里,我也不想在这里,但天黑的太快想走早就来不及 )!有一个问题在我们眼前!现在有三个字符串
s
1
s_1
s1,
s
2
s_2
s2 和
o
o
o,表示两个数字和一个操作类型,那么我们该怎么样得到算式的长度?
显然,一个算式由 5 5 5 个部分组成:第一个数 s 1 s_1 s1,一个符号 o o o,第二个数 s 2 s_2 s2,一个等号 = = =,结果的长度 m m m, 那么就是 l e n ( s 1 ) + l e n ( s 2 ) + m + 2 len(s_1)+len(s_2)+m+2 len(s1)+len(s2)+m+2,可是 m m m 又怎么算呢!
把 s 1 s_1 s1 和 s 2 s_2 s2 变成两个 i n t int int 类型的变量,可以用 s t o i ( ) stoi() stoi() 方法(就是 string to integer, 字符串转整数),接着将两个数相加,再转成字符串,可以用 t o _ s t r i n g ( ) to\_string() to_string() 方法,最后求他的长度,这就是 m m m!
所以,上代码!
#include <bits/stdc++.h>
using namespace std;
int n; // 为了循环方便,改用 n
string op, num1, num2, last_op;
int main() {
cin >> n;
for (int i = 1;i <= n;i ++) {
cin >> op >> num1;
if (op != "a" && op != "b" && op != "c") {
if (last_op == "a")
cout << op << "+" << num1 << "=" << stoi(op) + stoi(num1) << endl << op.length() + num1.length() + to_string(stoi(op) + stoi(num1)).length() + 2 << endl;
else if (last_op == "b")
cout << op << "-" << num1 << "=" << stoi(op) - stoi(num1) << endl << op.length() + num1.length() + to_string(stoi(op) - stoi(num1)).length() + 2 << endl;
else // 不是加和减,就是乘
cout << op << "*" << num1 << "=" << stoi(op) * stoi(num1) << endl << op.length() + num1.length() + to_string(stoi(op) * stoi(num1)).length() + 2 << endl;
}
else {
cin >> num2;
last_op = op; // 一定要记住改啊!!
if (op == "a")
cout << num1 << "+" << num2 << "=" << stoi(num1) + stoi(num2) << endl << num1.length() + num2.length() + to_string(stoi(num1) + stoi(num2)).length() + 2 << endl;
else if (op == "b")
cout << num1 << "-" << num2 << "=" << stoi(num1) - stoi(num2) << endl << num1.length() + num2.length() + to_string(stoi(num1) - stoi(num2)).length() + 2 << endl;
else
cout << num1 << "*" << num2 << "=" << stoi(num1) * stoi(num2) << endl << num1.length() + num2.length() + to_string(stoi(num1) * stoi(num2)).length() + 2 << endl;
}
}
}
总结:
s
t
o
i
(
s
)
stoi(s)
stoi(s) 能把字符串
s
s
s 转成整数
t
o
_
s
t
r
i
n
g
(
i
)
to\_string(i)
to_string(i) 能把整形
i
i
i 转成字符串