在计数时记得特殊判断0的长度为1:
int count(int x){
if(x==0) return 1;//特判
int res=0;
if(x<0) res++;
while(x!=0){
x/=10;
res++;
}
return res;
}
AC_code:
#include<iostream>
#include<sstream>
using namespace std;
int n,x,y;
char op;
string s;
int count(int x){
if(x==0) return 1;
int res=0;
if(x<0) res++;
while(x!=0){
x/=10;
res++;
}
return res;
}
void show(char op,int x,int y){
if(op=='a') cout<<x<<"+"<<y<<"="<<x+y<<endl<<2+count(x)+count(y)+count(x+y)<<endl;
else if(op=='b') cout<<x<<"-"<<y<<"="<<x-y<<endl<<2+count(x)+count(y)+count(x-y)<<endl;
else cout<<x<<"*"<<y<<"="<<x*y<<endl<<2+count(x)+count(y)+count(x*y)<<endl;
}
int main(){
cin>>n;
getchar();
while(n--){
getline(cin,s);
int flag=0;
for(int i=0;i<s.size();i++) if(s[i]==' ') flag++;
stringstream in(s);
if(flag==1) in>>x>>y;
else in>>op>>x>>y;
show(op,x,y);
}
return 0;
}