90分求助!#2 wa了

P1957 口算练习题

liuyinuo666 @ 2023-08-31 21:39:22

#include<bits/stdc++.h>
using namespace std;
#define ll long long
ll n;
ll cd(ll num)
{
    ll len=0;
    if(num==0)
    {
        return 1;
    }
    while(num!=0)
    {
        len++;
        num=num/10;
    }
    return len;
}
int main()
{
   cin>>n;
   for(int i=0;i<n;i++)
   {
      char a,t,g;
      ll b,c;
      cin>>a>>b>>c;
      if(a>='1' and a<='9')
         {
            b=b+((pow(10,cd(b))*(a-'0')));a=g;      
         }                            
      else g=a;
      ll ans;
      if(a=='a') ans=b+c,t='+';
      if(a=='b') ans=b-c,t='-';
      if(a=='c') ans=b*c,t='*';
      cout<< b<<t<<c<<'='<<ans<<endl;
      if(ans<0)  cout<< cd(ans)+cd(b)+cd(c)+3<<endl;
      else        cout<< cd(ans)+cd(b)+cd(c)+2<<endl; 
   }
}

by 违规用户名920406 @ 2023-08-31 21:48:25

那可能是读入的问题,有可能每行只有两个数,却读入了三个,就可能吧下一个数字吸收掉,例如

3
+ 1 2
3 4
5 6

by Null_h @ 2023-08-31 21:50:51

楼上正解,应特判或使用sscanf


#include<bits/stdc++.h>
using namespace std;
char c;
int a,d,e,f;
char s[5050],g[1000];
int main(){
    cin>>a;
    while(a--){
        cin>>g;
        if(g[0]!='a'&&g[0]!='b'&&g[0]!='c'){
            sscanf(g,"%d",&d);
            cin>>e;
        }else{
            c=g[0];
            cin>>d>>e;
        }
        if(c=='a'){
            sprintf(s,"%d+%d=%d",d,e,d+e);
        }else if(c=='b'){
            sprintf(s,"%d-%d=%d",d,e,d-e);
        }else{
            sprintf(s,"%d*%d=%d",d,e,d*e);
        }
        cout<<s<<endl<<strlen(s)<<endl;
    }
    return 0;
}

|