基础算法 —— 高精度计算 —— 高精度减法

【算法分析】

类似加法,可以用竖式求减法。在做减法运算时,需要注意的是:被减数必须比减数大,同时需要处理错位以及前导0。

【模版】

#include<iostream>
#include<cstring>
#include<string>
using namespace std;
int main()
{
    char str1[256],str2[256],temp[256];
    int a[256],b[256],c[256];
    int lena,lenb,lenc;
    int i;

    memset(a,0,sizeof(a));
    memset(b,0,sizeof(b));
    memset(c,0,sizeof(c));

    cin>>str1;//输入被减数
    cin>>str2;//输入减数

    lena=strlen(str1);
    lenb=strlen(str2);
    if( (lena<lenb) || (lena==lenb&&strcmp(str1,str2)) )//如果被减数小于减数,值为负,两者交换
    {
        strcpy(temp,str1);
        strcpy(str1,str2);
        strcpy(str2,temp);
        cout<<"-";//输出-
    }

    lena=strlen(str1);
    lenb=strlen(str2);

    for(i=0;i<=lena-1;i++)//被减数str1存入数组a
        a[lena-i]=str1[i]-'0';
    for(i=0;i<=lenb-1;i++)//减数str2存入数组b
        b[lenb-i]=str2[i]-'0';

    i=1;
    while(i<=lena||i<=lenb)
    {
        if(a[i]<b[i])
        {
            a[i]+=10;//借位
            a[i+1]--;//上一位减1
        }
        c[i]=a[i]-b[i];//对应位相减
        i++;
    }
    lenc=i;
    while((c[lenc]==0)&&(lenc>1))//删除前导0
        lenc--;

    for(i=lenc;i>=1;i--)//倒序输出
        cout<<c[i];
    cout<<endl;
    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值