zoukankan      html  css  js  c++  java
  • 高精度加法的C++实现

    精度计算——加法

    语法:add(char a[],char b[],char s[]);

    参数:

    a[]:被乘数,用字符串表示,位数不限

    b[]:乘数,用字符串表示,位数不限

    t[]:结果,用字符串表示

    返回值:null

    注意:

    空间复杂度为 o(n^2)

    需要 string.h

    源程序:

           void add(char a[],char b[],char back[])

          {

              int i,j,k,up,x,y,z,l;

              char *c;

              if (strlen(a)>strlen(b)) l=strlen(a)+2; else l=strlen(b)+2;

              c=(char *) malloc(l*sizeof(char));

              i=strlen(a)-1;

              j=strlen(b)-1;

              k=0;up=0;

              while(i>=0||j>=0)

                  {

                      if(i<0) x='0'; else x=a[i];

                      if(j<0) y='0'; else y=b[j];

                      z=x-'0'+y-'0';

                      if(up) z+=1;

                      if(z>9) {up=1;z%=10;} else up=0;

                      c[k++]=z+'0';

                      i--;j--;

                  }

              if(up) c[k++]='1';

              i=0;

              c[k]='\0';

              for(k-=1;k>=0;k--)

                  back[i++]=c[k];

              back[i]='\0';

          }

    void add(char a[],char b[],char back[])
    {
    int i,j,k,up,x,y,z,l;
    char *c;
    if (strlen(a)>strlen(b)) l=strlen(a)+2; else l=strlen(b)+2;
    c
    =(char *) malloc(l*sizeof(char));
    i
    =strlen(a)-1;
    j
    =strlen(b)-1;
    k
    =0;up=0;
    while(i>=0||j>=0)
    {
    if(i<0) x='0'; else x=a[i];
    if(j<0) y='0'; else y=b[j];
    z
    =x-'0'+y-'0';
    if(up) z+=1;
    if(z>9) {up=1;z%=10;} else up=0;
    c[k
    ++]=z+'0';
    i
    --;j--;
    }
    if(up) c[k++]='1';
    i
    =0;
    c[k]
    ='\0';
    for(k-=1;k>=0;k--)
    back[i
    ++]=c[k];
    back[i]
    ='\0';
    }
  • 相关阅读:
    cf C. Vasya and Robot
    zoj 3805 Machine
    cf B. Vasya and Public Transport
    cf D. Queue
    cf C. Find Maximum
    cf B. Two Heaps
    cf C. Jeff and Rounding
    cf B. Jeff and Periods
    cf A. Jeff and Digits
    I Think I Need a Houseboat
  • 原文地址:https://www.cnblogs.com/kuangbin/p/2113836.html
Copyright © 2011-2022 走看看