全WA,样例能过,求指点

P1957 口算练习题

Coral_Swallow @ 2021-01-29 23:03:37

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
string s;
int n,l;
int ans=2,i;
int a,b;
char x;
void init()
{
    a=0;
    b=0;
    ans=2;
    i=0;
}
void add()
{
    //printf("%d+%d=%d\n",a,b,a+b);
    cout<<a<<"+"<<b<<"="<<a+b<<endl;
    int c=a+b;
    while(c!=0)
    {
        c/=10;
        ans++;
    }
    //printf("%d\n",ans);
    cout<<ans<<endl;
}
void reduce()
{
    //printf("%d-%d=%d\n",a,b,a-b);
    cout<<a<<"-"<<b<<"="<<a-b<<endl;
    int c=a+b;
    if(c<=0)ans++;
    while(c!=0)
    {
        c/=10;
        ans++;
    }
    //printf("%d\n",ans);
    cout<<ans<<endl;
}
void mutiply()
{
    //printf("%d*%d=%d\n",a,b,a*b);
    cout<<a<<"*"<<b<<"="<<a*b<<endl;
    long long c=a*b;
    while(c!=0)
    {
        c/=10;
        ans++;
    }
    //printf("%d\n",ans);
    cout<<ans<<endl;
}
int main()
{
    cin>>n;
    while(n--)
    {
        init();
        getline(cin,s);
        l=s.length();
        if(s[0]>='a'&&s[0]<='c')x=s[0],i=2;
        for(;i<l;i++)
        {
            if(s[i]==' ')break;
            a*=10;
            a+=s[i]-48;
            ans++;
        }
        for(i+=1;i<l;i++)
        {
            b*=10;
            b+=s[i]-48;
            ans++;
        }
        switch(x)
        {
            case 'a':
                add();
                break;
            case 'b':
                reduce();
                break;
            case 'c':
                mutiply();
                break;
        }
    }
    return 0;
}

by KAMIYA_KINA @ 2021-01-30 08:18:05

建议把 getline 换成普通的读入再试试看。

你谷有些时候 getline 会出现奇怪的错误。


by KAMIYA_KINA @ 2021-01-30 08:39:59

建议换成这样读入

    while(n--) {
        cin >> a;//a,b为字符串
        if(a != "a" && a != "b" && a != "c") {
            cin >> b;
        } else {
            pre = a;
            cin >> a >> b;
        }
        if(pre == "a") add();
        else if(pre == "b") reduce();
        else multiply();
    }

by metaphysis @ 2021-01-30 13:28:21

@Coral_Swallow

如果输入在行首包含空格,您的代码无法正确处理,另外,在减法中存在问题:

void reduce()
{
    //printf("%d-%d=%d\n",a,b,a-b);
    cout<<a<<"-"<<b<<"="<<a-b<<endl;
    int c=a+b;
    if(c<=0)ans++;
    while(c!=0)
    {
        c/=10;
        ans++;
    }
    //printf("%d\n",ans);
    cout<<ans<<endl;
}

其中的:

int c = a + b;
if (c <= 0) ans++;

应为:

int c = a - b;
if (c < 0) ans++;

by Coral_Swallow @ 2021-01-30 22:44:24

@metaphysis @woody_wong 谢谢两位指点


|