C++ 80%求救

P1957 口算练习题

Opentds @ 2023-04-21 17:08:27

#include<iostream>
#include<cstdlib>
#include<cstring>

using namespace std;

const int N=50;

int judge(int n){
    int sum=0;
    while(n){
        n/=10;
        sum++;
    }
    return sum;
}

int main(){
    int i;
    cin>>i;
    char s[N];

    for(int t=0;t<i;t++){
        string a;
        cin>>a;
        if(a=="a"){
            s[t]='a';
            int b,c;
            cin>>b>>c;
            int res=b+c;
            cout<<b<<"+"<<c<<"="<<res<<endl;
            cout<<judge(b)+judge(c)+judge(res)+2<<endl;
        }
        else if(a=="b"){
            s[t]='b';
            int b,c;
            cin>>b>>c;
            int res=b-c;
            cout<<b<<"-"<<c<<"="<<res<<endl;
            if(res>=0)cout<<judge(b)+judge(c)+judge(res)+2<<endl;
            else cout<<judge(b)+judge(c)+judge(res)+3<<endl;
        }
        else if(a=="c"){
            s[t]='c';
            int b,c;
            cin>>b>>c;
            int res=b*c;
            cout<<b<<"*"<<c<<"="<<res<<endl;
            cout<<judge(b)+judge(c)+judge(res)+2<<endl;
        }
        else {
            int b=stoi(a);
            int c;
            cin>>c;
            if(s[t-1]=='a'){
                s[t]='a';
                int res=b+c;
                cout<<b<<"+"<<c<<"="<<res<<endl;
                cout<<judge(b)+judge(c)+judge(res)+2<<endl;
            }
            else if(s[t-1]=='b'){
                s[t]='b';
                int res=b-c;
                cout<<b<<"-"<<c<<"="<<res<<endl;
                if(res>=0)cout<<judge(b)+judge(c)+judge(res)+2<<endl;
                else cout<<judge(b)+judge(c)+judge(res)+3<<endl;
            }
            else if(s[t-1]=='c'){
                s[t]='c';
                int res=b*c;
                cout<<b<<"*"<<c<<"="<<res<<endl;
                cout<<judge(b)+judge(c)+judge(res)+2<<endl;
            }
        }

    }
    return 0;
}

by Yearn @ 2023-04-21 17:41:30

N的值没有限制吧


by winterl @ 2023-04-22 23:43:25

很简单,你的judge函数,在处理n=0的情况的时候,返回的是0,而应该返回1,所以只要把你的judge函数改成以下就好了

int judge(int n){
    if(n == 0)
        return 1;
    int sum=0;
    while(n){
        n/=10;
        sum++;
    }
    return sum;
}

|