高精度 兩小數相加

來源:互聯網
上載者:User

 

題目連結:http://acm.hdu.edu.cn/showproblem.php?pid=1753

題目大意:求兩個長小數的和

 

#include<iostream>#include<cmath>#include<cstdio>#include<cstdlib>#include<string>#include<cstring>#include<algorithm>#include<vector>#include<map>#define eps 1e-6#define INF (1<<20)#define PI acos(-1.0)using namespace std;char a[600],b[600];int lena,lenb,inta[600],intb[600],ans[600];int main(){    while(scanf("%s%s",a,b)!=EOF)    {        memset(inta,0,sizeof(inta));        memset(intb,0,sizeof(intb));        memset(ans,0,sizeof(ans));        lena=strlen(a);        lenb=strlen(b);        int i=lena-1;        while(a[i]!='.')            i--;        int tempa;        if(i<0)        {            tempa=0;            lena++;  //如果是整數,統一起來        }        else            tempa=lena-1-i;        int j=lenb-1;        while(b[j]!='.')            j--;        int tempb;        if(j<0)        {            tempb=0;            lenb++;        }        else            tempb=lenb-1-j;        int later=max(tempa,tempb); //最大的小數點後面的位元        for(i=later,j=lena-tempa;i>=1&&j<lena;i--)        {            inta[i]=a[j]-'0';            j++;        } //小數點後面的        for(i=1,j=later+1;i<=lena-1-tempa;i++,j++)            inta[j]=a[lena-1-tempa-i]-'0';//小數點前面的        int temp=j-1;        for(i=later,j=lenb-tempb;i>=1&&j<lenb;i--)        {            intb[i]=b[j]-'0';            j++;        }        for(i=1,j=later+1;i<=lenb-1-tempb;i++,j++)            intb[j]=b[lenb-tempb-1-i]-'0';        if(j-1>temp)            temp=j-1;        for(i=1;i<=temp;i++)        {            ans[i]+=inta[i]+intb[i];            if(ans[i]>=10)                ans[i+1]=ans[i]/10;            ans[i]=ans[i]%10;        }        while(ans[i]==0&&i>later+1)//去掉前置零,注意只能去掉小數點前一位前的零            i--;        if(i<=0)        {            printf("0\n");            continue;        }        for(j=1;ans[j]==0&&j<=later;j++);//去掉後置零,注意是小數點後面的零        for(;i>=j;i--)        {            if(i==later)                putchar('.');            printf("%d",ans[i]);        }        putchar('\n');    }    return 0;}/*0.001  0.00999999 11.0 912 245*/

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.