C语言,0分求助!

P1957 口算练习题

UTAsriel @ 2023-03-01 20:17:39

代码如下:

#include <ctype.h>

int nl(int n){
    int x=0;
    do{
        x++;
        n/=10;
    }while(n!=0);
    return x;
}

int main(void){
    int a,b,i;
    char x,y;
    scanf("%d",&i);
    for(int j=1;j<=i;j++){
        scanf("%c",&y);
        if(isalpha(y)){
            x=y;
            scanf("%d %d",&a,&b);
        }
        else{
            a=y*1;
            scanf("%d",&b);
        }
        if(x=='a'){
            printf("%d+%d=%d\n%d\n",a,b,a+b,nl(a)+nl(b)+nl(a+b)+2);
        }
        else if(x=='b'){
            printf("%d-%d=%d\n%d\n",a,b,a-b,nl(a)+nl(b)+nl(a-b)+2);
        }
        else if(x=='c'){
            printf("%d*%d=%d\n%d\n",a,b,a*b,nl(a)+nl(b)+nl(a*b)+2);
        }
    }
    return 0;
}

(用DEV C++测试的时候发现第二行第一个一不管输入是不是字母,它都会执行else部分,这是为什么?)


by Sun_Email @ 2023-03-01 20:22:17

建议直接用一个char[]读入


by Sun_Email @ 2023-03-01 20:22:34

(就是用%s)


by Sun_Email @ 2023-03-01 20:26:41

#include<bits/stdc++.h> 
int nl(int n){
    int x=0;
    if(n<0){
        ++x;n*=-1;
    }
    do{
        x++;
        n/=10;
    }while(n!=0);
    return x;
}
using namespace std;
int main(void){
    int a,b,i;
    char x,y[3];
    scanf("%d",&i);
    for(int j=1;j<=i;j++){
        scanf("%s",y);
        if(isalpha(y[0])){
            x=y[0];
            scanf("%d %d",&a,&b);
        }
        else{
            a=0;
            for(int k=0;k<strlen(y);++k){
                a=a*10+(y[k]-'0');
            }
            scanf("%d",&b);
        }
        if(x=='a'){
            printf("%d+%d=%d\n%d\n",a,b,a+b,nl(a)+nl(b)+nl(a+b)+2);
        }
        else if(x=='b'){
            printf("%d-%d=%d\n%d\n",a,b,a-b,nl(a)+nl(b)+nl(a-b)+2);
        }
        else if(x=='c'){
            printf("%d*%d=%d\n%d\n",a,b,a*b,nl(a)+nl(b)+nl(a*b)+2);
        }
    }
    return 0;
}

样例过的


by Sun_Email @ 2023-03-01 20:26:53

@UTAsriel


by UTAsriel @ 2023-03-03 15:20:31

@Sun_Email 感谢大佬指教!


|