A-B problem(高精度减法)

A-B problem

题目传送门
Description
Now, Give you two intgers A and B , Please calculate the value of A minus B.
Attation: A、Band A-B are all non-negative numbers.

Input
Each line will contain two integers AA and BB.Process to end of file.(EOFEOF)

Output
For each case, Please output the value of A minus B

Sample Input 1
5 3
4 1

Sample Output 1
2
3
由于这个题的数据比较大,无法用long long int 表示,所以要用数组模拟这一减法问题。要注意进行完一次运算后对数组进行初始化。

#include<stdio.h>
int main()
{
    char x[1000],y[1000];
    int l[1000],m[1000],len1,len2;
    while(scanf("%s%s",&x,&y)!=EOF)
    {
        for(int i=0;i<1000;i++)
            {l[i]=0;m[i]=0;}
        len1=strlen(x);len2=strlen(y);
        for(int i=0,j=len1-1;j>=0;j--,i++)
  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
大数减法问题通常可以使用字符串来表示大整数,然后模拟手工减法的过程来求解。具体思路如下: 1. 将两个大数用字符串表示,并将其逆序存储,方便从低位到高位进行操作。 2. 从最低位开始,依次计算两个大数对应位的差值,如果被减数小于减数,则需要向高位借位。 3. 如果被减数的长度大于减数的长度,则需要将被减数剩余的高位继续减去借位的值。 4. 最后将得到的结果字符串再次逆序输出即为最终结果。 下面是 C 语言的实现代码,其中用到了字符数组的逆序操作和进位处理: ```c #include <stdio.h> #include <string.h> int main() { char a[1005], b[1005], c[1005]; int la, lb, lc, i, x, y, z; // 读入两个大数 scanf("%s%s", a, b); la = strlen(a); lb = strlen(b); // 逆序存储 for (i = 0; i < la / 2; i++) { x = a[i]; a[i] = a[la - i - 1]; a[la - i - 1] = x; } for (i = 0; i < lb / 2; i++) { x = b[i]; b[i] = b[lb - i - 1]; b[lb - i - 1] = x; } // 从低位到高位逐位相减 lc = 0; for (i = 0; i < la || i < lb; i++) { x = (i < la) ? (a[i] - '0') : 0; y = (i < lb) ? (b[i] - '0') : 0; z = x - y - c[i]; if (z < 0) { c[i] = z + 10; c[i + 1] = 1; } else { c[i] = z; c[i + 1] = 0; } lc = i + 1; } // 处理高位借位 while (lc > 1 && c[lc - 1] == 0) { lc--; } // 逆序输出结果 for (i = lc - 1; i >= 0; i--) { printf("%d", c[i]); } printf("\n"); return 0; } ``` 需要注意的是,上述代码中只实现了大数减法的基本功能,对于错误输入和特殊情况(如减数大于被减数)没有进行判断和处理,需要根据实际情况进行修改和完善。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值