wiki oi 3115高精度练习之减法

题目描述 Description

给出两个正整数A和B,计算A-B的值。保证A和B的位数不超过500位。

输入描述 Input Description

读入两个用空格隔开的正整数

输出描述 Output Description

输出A-B的值

样例输入 Sample Input

3 12

样例输出 Sample Output

-9

数据范围及提示 Data Size & Hint

两个正整数的位数不超过500位

代码:

 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<math.h>
 4 #include<iostream>
 5 #include<algorithm>
 6 using namespace std;
 7 char a[501],b[501];
 8 int c[500];
 9 int cp(char a[],char b[])//比较两个大数的大小,a大返回1,b大返回2,一样大返3;
10 {
11     int i=strlen(a),j=strlen(b);
12     if(i>j)return 1;
13     else if(j>i)return 2;
14     else if(i==j)
15     {
16         for(int k=0; k<j; k++)
17         {
18             if(a[k]>b[k])return 1;
19             if(a[k]<b[k])return 2;
20         }
21         return 3;
22     }
23 }
24 int main()
25 {
26     memset(c, 0, sizeof(c));
27     cin>>a>>b;
28     int cmp=cp(a,b);
29     if(cmp==3)printf("0
"); //一样大直接输出0;
30     int lena=strlen(a);
31     int lenb=strlen(b);
32     int i=lena-1,j=lenb-1,k=0;//注意长度减一;
33     int carry=0;//设置进位,开始为0;
34     while(i>=0&&j>=0)//先处理两个大数在相同位数那一段相减;模拟手算
35     {
36         int cc;//注意a,b转换成int型
37         if(cmp==1)cc=(a[i]-'0')-(b[j]-'0')-carry;//如果a大,用a-b;
38         else if(cmp==2)cc=(b[j]-'0')-(a[i]-'0')-carry;//b大,用b-a;
39         if(cc<0)//减了要判断是不是负数
40         {
41             c[k++]=cc+10;//负数要加10;
42             carry=1;//加10后要向前-1;
43             i--;j--;
44         }
45         else
46         {
47             c[k++]=cc;//正数直接赋值
48             carry=0;//进位不用减
49             i--;j--;
50         }
51     }
52 /*  调试代码,你懂得!
53     for(int l=k;l>=0;l--)printf("%d",c[l]);printf("
");
54     printf("%d %d
",i,j);
55     下面处理多出的那一段;
56 */
57     if(cmp==1&&i>=0){//a长些或者大些就把a多出b的部分直接赋值给c,注意同时进位也得继续补上,避免1000-1跪;
58             while(i>=0){
59                 int cc=a[i--]-'0'-carry;//同样转int
60                 if(cc<0){c[k++]=cc+10;carry=1;}
61                 else {c[k++]=cc;carry=0;}
62             }
63     }
64     if(cmp==2&&j>=0){//b长些或者大些就把b多出a的部分直接赋值给c,注意同时进位也得继续补上,避免1000-1跪;
65             while(j>=0){
66                 int cc=b[j--]-'0'-carry;//同样转int
67                 if(cc<0){c[k++]=cc+10;carry=1;}
68                 else {c[k++]=cc;carry=0;}
69             }
70     }
71     if(cmp==2)printf("-");//b大就输出负号;
72     int last=0;
73     for(int l=0;l<k;l++)if(c[l]!=0)last=l;//找出第一个不为0的数
74     for(int l=last;l>=0;l--)printf("%d",c[l]);//因为是从c[0]开始先存个位,所以倒着输出
75     printf("
");
76     return 0;
77 }
随便写写。一点学习心得。。。--如果本文章没有注明转载则为原创文章,可以随意复制发表,但请注明出处与作者
原文地址:https://www.cnblogs.com/ganhang-acm/p/4187948.html