zoukankan      html  css  js  c++  java
  • 《信息学奥赛一本通》 高精度减法。输入两个正整数,求它们的差。

    算法分析

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

    代码如下:

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    using namespace std;
    int main ()
    {
     int a[256],b[256],c[256],lena,lenb,lenc,i;
     char n[256],n1[256],n2[256];
     memset(a,0,sizeof(a));
     memset(b,0,sizeof(b));
     memset(c,0,sizeof(c));
     gets(n1);
     gets(n2);
     //输入被减数和被减数
     if(strlen(n1)<strlen(n2)||(strlen(n1)==strlen(n2)&&strcmp(n1,n2)<0))
     {
      //strcmp()为字符串比较函数,当n1==n2时,返回0;当n1>n2时,返回正整数;当n1<n2时,返回负整数。
      //处理被减数和减数,交换被减数和减数
      strcpy(n,n1);
      strcpy(n1,n2);
      strcpy(n2,n);
      cout<<"-";
      //交换了减数和被减数,结果为负数。
     }
     lena=strlen(n1);
     lenb=strlen(n2);
     for(i=0;i<=lena-1;i++)
     {//被减数放入a数组
      a[lena-i]=int(n1[i]-'0');
     }
     for(i=0;i<=lena-1;i++)
     {//减数放入b数组
      b[lena-i]=int(n2[i]-'0');
     }
     i=1;
     while(i<=lena||i<=lenb)
     {
      if(a[i]<b[i])
      {//不够减,那么向高位借1当10
       a[i]+=10;
       a[i+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;
    }
    

    升级版代码

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    using namespace std;
    int main ()
    {
    	int a[256],b[256],c[256],lena,lenb,lenc,i;
     	char n[256],n1[256],n2[256];
    	memset(a,0,sizeof(a));
    	memset(b,0,sizeof(b));
    	memset(c,0,sizeof(c));
    	cin>>n1>>n2;
    	lena=strlen(n1);
    	lenb=strlen(n2);
    	if(lena<lenb||(lena==lenb&&strcmp(n1,n2)<0))
    	{
    		strcpy(n,n1);
    		strcpy(n1,n2);
    		strcpy(n2,n);
    		cout<<"-";
    	}
    	lena=strlen(n1);
    	lenb=strlen(n2);
    	for(i=0;i<=lena-1;i++)a[lena-i]=n1[i]-'0';
    	for(i=0;i<=lenb-1;i++)b[lenb-i]=n2[i]-'0';
    	i=1;
    	while(i<=lena||i<=lenb)
    	{
    		if(a[i]<b[i])
    		{
    			a[i]+=10;
    			a[i+1]--;
    		}
    		c[i]=a[i]-b[i];
    		i++;
    	}
    	lenc=i;
    	bool temp=true;
    	for(i=lenc;i>=1;i--)
    	{
    		if(c[i]==0&&temp==true)continue;
    		else temp=false;
    		cout<<c[i];
    	}
    	cout<<endl;
    	return 0;
    }
    
  • 相关阅读:
    49. 字母异位词分组
    73. 矩阵置零
    Razor语法问题(foreach里面嵌套if)
    多线程问题
    Get json formatted string from web by sending HttpWebRequest and then deserialize it to get needed data
    How to execute tons of tasks parallelly with TPL method?
    How to sort the dictionary by the value field
    How to customize the console applicaton
    What is the difference for delete/truncate/drop
    How to call C/C++ sytle function from C# solution?
  • 原文地址:https://www.cnblogs.com/AlexKing007/p/12339606.html
Copyright © 2011-2022 走看看