高精度减法

本文介绍了一种使用C++实现两个字符串表示的大数相减的方法。通过将字符串转换为字符数组并进行逐位减法运算,实现了大整数相减的功能。该程序能够正确处理正负号及不同长度的输入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

c++

#include <iostream>
#include <string.h>

using namespace std;

int main()
{
    char A[201]={},B[201]={};
    int a[200]={},b[200]={},sub[200]={};
    cin>>A>>B;
    int sign;
    int lenA=strlen(A),lenB=strlen(B);
    if(lenA==lenB){
        sign=strcmp(A,B);
    if(lenA<lenB){
        sign=-1;
        }
    }


    if(sign<0){
        swap(A,B);
    }
    lenA=strlen(A);
lenB=strlen(B);

    for(int i=0;i<lenA;i++){
        a[lenA-i-1]=A[i]-'0';
    }
    for(int i=0;i<lenB;i++){
        b[lenB-i-1]=B[i]-'0';
    }
    int lenS=0;
    while(lenS<lenA||lenS<lenB){
        if(a[lenS]<b[lenS]){
            a[lenS]+=10;
            a[lenS+1]--;
        }
        sub[lenS]=a[lenS]-b[lenS];
        lenS++;
    }

    if(sign<0){
        cout <<"-";
    }
    while(sub[lenS]==0&&lenS>0){
        lenS--;
    }
    for(int i=lenS;i>=0;i--){
        cout <<sub[i];
    }
    return 0;
}
 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值