Pat B1024/A1073科学计数法

字符串处理问题,不是很难。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>

using namespace std;

const int MaxVector = 10005;

int main(){
    char ch[MaxVector];
    scanf("%s",ch);//用字符串接受

    int len = strlen(ch);//判断长度
    int clen = 0;//定义常数项的长度
    char c[MaxVector];//将常数项放入一个 数组中
    int i;
    //分离常数 不带+-号
    for(i = 1;ch[i] != 'E';i ++){
        c[clen ++] = ch[i];
    }
    //分离指数 带+-号
    char e[MaxVector];
    int elen = 0;
    for(i ++ ;i < len;i ++){
        e[elen ++] = ch[i];
    }

    //指数int化,无符号,均为正数
    int esum = 0;
    int p = 1;
    for(i = elen - 1; i > 0;i --){

        esum += p * (e[i] - '0');
        p *= 10;

    }

//做题关键是判断小数点的移动,以及特殊位置小数点的如何处理。
    if(e[0] == '-'){//通过指数正负号来处理

        reverse(c,c+clen);//先反转,因为小数点要向前移动。
        if(esum  == 0){//判断小数点是否要移动
            reverse(c,c+clen);
        }
        int clentemp = clen;//因为常数字符串被反转,指数为负数时,小数点要向后移动。该变量最后就是字符串的长度。
        if(esum > 0){

            char temp;//先做一次变换。
            temp = c[clentemp - 1];
            c[clentemp - 1] = c[clentemp - 2];
            c[clentemp - 2] = temp;
            c[clentemp ++] = '0';
            for(int j = 1;j < esum;j ++){//继续余下的变换
                char temp;
                temp = c[clentemp - 1];
                c[clentemp - 1] = c[clentemp - 2];
                c[clentemp - 2] = temp;
                c[clentemp ++] = '0';
            }
            reverse(c,c + clentemp);
        }

        if(ch[0] == '-'){//若常数为负数加上负号
            printf("-");
        }
        for(int i = 0;i < clentemp;i ++){
            printf("%c",c[i]);
        }

    }else if(e[0] == '+'){
        //clen c[] 常数
        //esum 指数
        int clentemp = clen;
        int j = clen;

        int flag = 0;
        if(esum  > 0){//1.2 1
            j = 1;
            for(int i = 1;i <= esum;i ++){

                if(i <= clen - 2){//.向后移
                    char temp = c[j];
                    c[j] = c[j + 1];
                    c[j + 1] = temp;
                    j ++;
               
                }else if(i == clen - 1){//去.加0
                    c[j] = '0';
                    j++;
                }else{//加0
                    c[j] = '0';
                    j++;
                }
            }

            if(j  < clen){
                j = clen;

            }
        }
        if(clen - 2 == esum){//需要判断,小数点后的位数与需要向后移动的位数相同时的情况,应该去掉小数点。
            j --;
        }
        if(ch[0] == '-'){
            printf("-");
        }
        for(int i = 0;i < j;i ++){
            printf("%c",c[i]);
        }
    }


    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值