当前位置:网站首页>High precision subtraction

High precision subtraction

2022-07-05 05:20:00 hunziHang

#include<bits/stdc++.h>
using namespace std;
int compare(string s1,string s2)
{
    int i;
    if(s1.length()>s2.length())
        return 0;
    else if(s1.length()<s2.length())
      return 1;
      else
      {
          for(i=0;i<=s1.length();i++)
          {
              if(s1[i]>s2[i])
                return 0;
              else if(s1[i]<s2[i])
                return 1;
          }
      }
      return 0;
}
int main()
{
    string s1,s2;
    int a[100000],b[100000],i,j;
      cin>>s1>>s2;
      memset(a,0,sizeof(a));
      memset(b,0,sizeof(b));
    a[0]=s1.length();
    b[0]=s2.length();
    for(i=1;i<=a[0];i++)
        a[i]=s1[a[0]-i]-'0';
    for(i=1;i<=b[0];i++)
        b[i]=s2[b[0]-i]-'0';
    if(compare(s1,s2)==0)
    {
        for(i=1;i<=a[0];i++)
        {
            a[i]-=b[i];
            if(a[i]<0)
            {
                a[i+1]--;
                a[i]+=10;
            }

        }
        a[0]++;
        while(a[a[0]]==0&&a[0]>1)
        {
            a[0]--;
        }
        for(i=a[0];i>=1;i--)
            cout<<a[i];
        cout<<endl;

    }
    else
    {
        cout<<"-";
        for(i=1;i<=b[0];i++)
        {
            b[i]-=a[i];
            if(b[i]<0)
            {
                b[i]+=10;
                b[i+1]--;
            }

        }
        b[0]++;
        while(b[b[0]]==0&&b[0]>1)
            b[0]--;
            for(i=b[0];i>=1;i--)
                cout<<b[i];
            cout<<endl;

    }


}

1. Judge the size , When the length is the same   if(s1[i]>s2[i]) return 0; else return 1; Less consideration is given to equal situations ; Finally, if all are the same return 0;

2. After cutting , Long array   length ++;

3. This method is only applicable to Add two positive numbers ,  If the minuend is negative   ,  The output ’-‘ Into two numbers added , if , Minus is negative , Then add two numbers .( The first two can be merged , When outputting, we will discuss whether to output ’-‘).      All negative numbers , Convert to the next number - The previous number ( All positive numbers , And all negative numbers can be merged )

原网站

版权声明
本文为[hunziHang]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140622508805.html