在控制台输入数据可以得到正确答案,但为什么换成文件读入就会输出错误答案?

P1957 口算练习题

Castaways @ 2023-01-29 22:20:53

#include<bits/stdc++.h>
#define ywj(a) freopen(#a".in","r",stdin); //freopen(#a".out","w",stdout);
#define wlp ios::sync_with_stdio(false);
#define f1(i,a,b) for(register int i=a;i<=b;i++)
#define f2(i,a,b) for(register int i=a;i>=b;i--)
#define ll long long
#define maxn 1005
using namespace std;
int ans;
string s;
int wot(string x){
    bool vis=true;
    if(x[0]=='-') vis=false;
    else if(x[0]=='+') vis=true;
    unsigned short len=x.length();
    int num=0;
    ll xp=1;
    f2(i,len-1,0){
        if(x[i]=='-'||x[i]=='+') continue;
        num+=(x[i]-'0')*xp;
        xp*=10;
    }
    if(vis) return num;
    else return 0-num; 
}
int work(int x){
    int point=0;
    if(x<0) point++;
    while(x!=0){
        point++;
        x/=10;
    }
    return point;
}
int read(){
    int x=0,f=1;
    char ch=getchar();
    while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}
    while(isdigit(ch)){x=(x<<3)+(x<<1)+ch-48;ch=getchar();}
    return x*f;
}
void write(int x){
    if(x<0) putchar('-'),x=-x;
    if(x>9) write(x/10);
    putchar(x%10+'0');
}
int main(){
//  ywj(1957)
    wlp;
    int T;
    char last_op;
    T=read();
    while(T--){
        ans=2;
        int point=0;
        int a,b,c;
        getline(cin,s);
        int len=s.length();
        if(!isdigit(s[0])){
            if(s[0]=='a') last_op='+';
            else if(s[0]=='b') last_op='-';
            else if(s[0]=='c') last_op='*';
        }
        string tmp;
        tmp.clear();
        f1(i,2,len-1){
            if(!isdigit(s[i])){point=i;break;}
            tmp+=s[i];
        }
        a=wot(tmp);ans+=work(a);
        tmp.clear();
        f1(i,point+1,len-1){
            if(!isdigit(s[i])) break;
            tmp+=s[i];
        }
        b=wot(tmp);ans+=work(b);
        if(last_op=='+') c=(a+b);
        else if(last_op=='-') c=(a-b);
        else if(last_op=='*') c=(a*b);
        ans+=work(c);
        write(a);putchar(last_op);write(b);putchar('=');write(c);puts("");
        write(ans);
        puts("");
    }
    return 0;
}

by Sprague_Garundy @ 2023-01-29 22:58:16

@Castaways 你都关同步了还混用 cin 和快读不挂才怪,而且 define 个关同步干嘛加分号,你自己下面写的时候还是要补分号啊


by Castaways @ 2023-01-30 08:59:01

@Sprague_Garundy

我把同步开了,而且在下载测试点后在本地跑是对的,但是在洛谷上提交以后又变成全WA了。能解释一下这是为什么吗?


by Mr_Biantainne @ 2023-01-30 17:29:41

@Castaways 洛谷系统很奇怪,使用getline就算本地对了交上去也是错的,能不用getline就不用,我也被坑了。


by Castaways @ 2023-01-30 19:02:13

@C20220215

洛谷太6了,以后再也不用getline了。


by Castaways @ 2023-01-30 19:56:19

问题是我用getsfgets,交上去都不行,在本地测试又是对的


by Castaways @ 2023-01-30 20:23:05

然后在本地跑出来的答案和在洛谷在线IDE中跑出来的答案不一样。


by Castaways @ 2023-01-30 20:36:53

OK,我AC了,此贴完结


|