C++80分求助

P1957 口算练习题

511_Juruo_wyk @ 2023-11-23 22:11:30

样例已过

#include<bits/stdc++.h>
using namespace std;
const int N = 11;
char last;
char c[N];
int a1,a2;
int len(int n){
    if(n>0)return int(1+log10(n));
    else return 1+int(1+log10(abs(n)));
}
void print(int a1,int a2,int s,char c){
    printf("%d%c%d=%d\n%d\n",a1,c,a2,s,len(a1)+len(a2)+len(s)+2);
    return;
}
int main(){
    int t;cin>>t;
    while(t--){
        scanf("%s",c);
        if(c[0]>='0'&&c[0]<='9')a1=atof(c),c[0]=last;
        else scanf("%d",&a1);
        switch(c[0]){
            case 'a':scanf("%d",&a2),print(a1,a2,a1+a2,'+');break;
            case 'b':scanf("%d",&a2),print(a1,a2,a1-a2,'-');break;
            case 'c':scanf("%d",&a2),print(a1,a2,a1*a2,'*');break;
        }
        last=c[0];
    }
    return 0;
}

by Dreamer_002 @ 2023-12-22 16:52:09

@511_Juruo_wyk 试试计算

len(0)

会出问题(-int极限)

所以长度有时是负的


by Dreamer_002 @ 2023-12-22 16:53:41

改成

int len(int n)
    int size=0;
    if(n==0)return 1;
    if(n<0){
        n=-n;
        size++;
    }
    while(n>0){
        n/=10;
        size++;
    }
    return size;
}

即可


by Dreamer_002 @ 2023-12-22 16:56:10

抱歉,缺大括号

#include<bits/stdc++.h>
using namespace std;
const int N = 11;
char last;
char c[N];
int a1,a2;
int len(int n){
    int size=0;
    if(n==0)return 1;
    if(n<0){
        n=-n;
        size++;
    }
    while(n>0){
        n/=10;
        size++;
    }
    return size;
}
void print(int a1,int a2,int s,char c){
    printf("%d%c%d=%d\n%d\n",a1,c,a2,s,len(a1)+len(a2)+len(s)+2);
    return;
}
int main(){
    int t;cin>>t;
    while(t--){
        scanf("%s",c);
        if(c[0]>='0'&&c[0]<='9')a1=atoi(c),c[0]=last;
        else scanf("%d",&a1);
        switch(c[0]){
            case 'a':scanf("%d",&a2),print(a1,a2,a1+a2,'+');break;
            case 'b':scanf("%d",&a2),print(a1,a2,a1-a2,'-');break;
            case 'c':scanf("%d",&a2),print(a1,a2,a1*a2,'*');break;
        }
        last=c[0];
    }
    return 0;
}

by Dreamer_002 @ 2023-12-22 16:56:26

过了


by Dreamer_002 @ 2023-12-22 16:57:01

@511_Juruo_wyk


by 511_Juruo_wyk @ 2023-12-22 18:43:41

@zhongruqian 谢谢,这题我之前换了一种方法过了,不过这种方法一直是令我苦恼的问题。感谢您帮我解决!


|