高精度减法算法

#include <iostream>
#include <cstring>
using namespace std;
void sub( char*str1,char* str2,char* c) //c返回结果
{
    int flag=1;     //1表示被减数str1大于减数str2,-1相反结果前要有负号
    int i,j;
    int len1=strlen(str1);
    int len2=strlen(str2);
    int max=len1>len2?len1:len2;
    char *tmp;
    if(len1<len2)
        flag=-1;
    else
    {
        if(len1==len2&&str1<str2)
            flag=-1;
    }
    if(flag==1)             //被减数长度大于减数长度,方便运算,要进行右对齐,减数前补0填充
    {
        j=len1-1;
        for(i=len2-1;i>=0;i--)
        {
            str2[j--]=str2[i];
        }
        str2[len1]='\0';
        for(i=j;i>=0;i--)
            str2[i]='0';

    }
    else                    //减数长度大于被减数
    {
        j=len2-1;
        for(i=len1-1;i>=0;i--)
        {
            str1[j--]=str1[i];
        }
        str1[len2]='\0';
        for(i=j;i>=0;i--)
            str1[i]='0';
    }
    cout<<"str1:"<<str1<<endl;
    cout<<"str2:"<<str2<<endl;
    int carry=0;
    if(flag==-1)
    {
        tmp=str1;
        str1=str2;
        str2=tmp;
    }
    for(i=max-1;i>=0;i--)       //每位进行减法运算
    {
        c[i]=(str1[i]-'0')-(str2[i]-'0')-carry+'0';
        if(c[i]-'0'<0)
        {
            c[i]=c[i]+10;
            carry=1;
        }
        else
        {
            carry=0;
        }
    }
    int pos=0;
    i=0,j=0;
    while(c[pos]-'0'==0)
        pos++;
    if(pos==0&&flag==-1)    //结果是负数要添负号
    {
        for(i=max-1;i>=0;i--)
            c[i+1]=c[i];
        c[0]='-';
        c[max+1]='\0';
    }
    else
    {
        if(flag==-1)
        {
            j=1;
            for(i=pos;i<max;i++)
                c[j++]=c[i];
            c[j]='\0';
            c[0]='-';
        }
        else
        {
            j=0;
            for(i=pos;i<max;i++)
                c[j++]=c[i];
            c[j]='\0';
        }
    }


}
int main()
{
    char str1[30],str2[30];
    char res[30];
    while(cin>>str1>>str2)
    {
        sub(str1,str2,res);
        cout<<res;
        cout<<endl;
    }
}
 
 


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值