PAT A1073 Scientific Notation

1073 Scientific Notation (20 分)

Scientific notation is the way that scientists easily handle very large numbers or very small numbers. The notation matches the regular expression [+-][1-9].[0-9]+E[+-][0-9]+ which means that the integer portion has exactly one digit, there is at least one digit in the fractional portion, and the number and its exponent's signs are always provided even when they are positive.

Now given a real number A in scientific notation, you are supposed to print A in the conventional notation while keeping all the significant figures.

Input Specification:

Each input contains one test case. For each case, there is one line containing the real number A in scientific notation. The number is no more than 9999 bytes in length and the exponent's absolute value is no more than 9999.

Output Specification:

For each test case, print in one line the input number A in the conventional notation, with all the significant figures kept, including trailing zeros.

Sample Input 1:

+1.23400E-03

Sample Output 1:

0.00123400

Sample Input 2:

-1.2E+10

Sample Output 2:

-12000000000

代码如下:

#include <stdio.h>
#include <string.h>

int main(){
    char s[10010];
    scanf("%s",s);
    int len=strlen(s);

    //是负数要输出负号
    if(s[0]=='-')
        printf("-");

    //获取小数点位置,和E的位置
    int pos_dot,pos_E,i=0;
    for(i=0;i<len;i++){
        if(s[i]=='.') pos_dot=i;
        if(s[i]=='E'){
            pos_E=i;
            break;
        }
    }

    //获取指数大小
    int exp=0;
    for(i=pos_E+2;i<len;i++){
        exp=exp*10+s[i]-'0';
    }

    //指数为正
    if(s[pos_E+1]=='+'){
        for(i=1;i<pos_E;i++){
            if(i==pos_dot) continue;   //小数点不输出
            printf("%c",s[i]);
            if(i==pos_dot+exp && i!=pos_E-1) printf(".");  //i==pos+exp表示i是要输出的小数点前一位,如果要输出的数字有小数位,会取到,没有小数位,就不会取到
                                                           //i!=pos_E-1表示i不是E前一位,因为此时没有小数位,无需输出小数点
        }
        for(i=0;i<exp-pos_E+pos_dot+1;i++){      //没有小数位的话,还要输出多少个0
            printf("0");
        }
    }

    //指数为正
    else if(s[pos_E+1]=='-'){
        pos_dot--;        //此时pos_dot表示小数点前有几位数字
        if(pos_dot-exp<=0) printf("0.");   //负号表示都是0.几的数字
        for(i=0;i<exp-pos_dot;i++)        //前面要补足多少个0
            printf("0");
        for(i=1;i<pos_E;i++){
            if(i==pos_dot+1) continue;
            printf("%c",s[i]);
            if(i==pos_dot-exp) printf(".");
        }

    }

}

猜你喜欢

转载自blog.csdn.net/qq_36525099/article/details/86688134