求助一下

P1957 口算练习题

lwhhwl08 @ 2022-06-23 23:53:05

自己测试都对,但是全WA

#include <stdio.h>
int calculate(char realtype,int m,int n){
    int result;

    switch (realtype){
        case 'a':
            result=m+n;
            break;
        case 'b':
            result=m-n;
            break;
        case 'c':
            result=m*n;
            break;
    }

    return result;
}

int length(int a){
    int r=1;
    int cnt=0;
    if(a>0){
        for(int i=10;r>0;i*=10,cnt++){
            r=a/i;
        }
    }
    else if(a==0){
        cnt=1;
    }
    else if(a<0){
        a=-a;
        for(int i=10;r>0;i*=10,cnt++){
            r=a/i;
        }
        cnt=cnt+1;
    }
    return cnt;
}

char trans(char realtype){
    char transc;
    if(realtype=='a') transc='+';
    if(realtype=='b') transc='-';
    if(realtype=='c') transc='*';
    return transc;
}

int main (){
    int num;
    scanf("%d",&num);getchar();
    char a[50];
    char b[50];
    char g[num][50];
    int leng[num];
    int result;
    int i=0;
    char type,realtype;
    int m,n;

    for(i=0;i<n;i++){
        for(int j=0;j<50;j++){
            g[i][j]=0;
        }
    } //初始化g数组元素全为0; 

    for(i=0;i<=num-1;i++){

        gets(a);

        sscanf(a,"%c",&type);
        if(type=='a'||type=='b'||type=='c'){ //此时对运算类型有重新定义; 
            sscanf(a,"%c %d %d",&realtype,&m,&n);
            result=calculate(realtype,m,n);
            sprintf(g[i],"%d%c%d=%d",m,trans(realtype),n,result);
            leng[i]=length(m)+length(n)+length(result)+2;
        }
        else{
            sscanf(a,"%d %d",&m,&n); //此时没有对运算类型重新定义; 
            result=calculate(realtype,m,n);
            sprintf(g[i],"%d%c%d=%d",m,trans(realtype),n,result);
            leng[i]=length(m)+length(n)+length(result)+2;
        }
    } 

    for(i=0;i<num;i++){
        printf("%s",g[i]);
        if(i<num-1) printf("\n%d\n",leng[i]);
        if(i==num-1) printf("\n%d",leng[i]);
    }

    return 0;
}

|