本题是个模拟,没有过多干货和思维, 楼上的题解用的是 C 语言中 char 数组来保存,本人还是觉得 STL 的 string 好用。 就是输入有点慢
但在此之前有几个超好用的函数介绍一下:
1.to_string() 将一个整数转化为 string 类型。
2.stoi() 将 string 类型中的数转化为 int 类型,便于进行运算。
3.isalpha() 判断一个字符是否为字母(大写或小写)。
用着很舒服,在保证可读性的同时减少了码量,话不多说,上 AC 代码!
#include<iostream>
#include<cstdio>
#include<cctype>
using namespace std;
int n;
string a,b,c;
char op;//用一个变量储存起来,保留上一个输入的运算符,优化判断代码
inline void solve(string x,string y){ //本题核心代码
string s;//用s表示结果,最后可以用s.length()表示长度,不必另求
int ans;
if(op=='a'){
ans=stoi(x)+stoi(y);
s=x+"+"+y+"="+to_string(ans);
}
else if(op=='b'){
ans=stoi(x)-stoi(y);
s=x+"-"+y+"="+to_string(ans);
}
else{
ans=stoi(x)*stoi(y);
s=x+"*"+y+"="+to_string(ans);
}
cout<<s<<'\n'<<s.length()<<'\n'; //集中处理
}
signed main(){
ios::sync_with_stdio(false),ios_base::sync_with_stdio(false),cin.tie(nullptr),cout.tie(nullptr);//加速输入
cin>>n;
for(int i=1;i<=n;i++){
cin>>a>>b;
if(isalpha(a[0])){ //表示第一个输入string是运算符,需要再输入一个数
op=a[0];
cin>>c;
solve(b,c); //将需要运算的数字传给solve函数,减少冗杂判断
}
else{
solve(a,b);
}
}
return 0;
}