zoukankan      html  css  js  c++  java
  • 高精度计算(三) /*高精度的减法运算*/

    高精度的减法运算

    求两个大的正整数相减的差。

    输入:

    共 2 行,第 1 行是被减数 a,第 2 行是减数 b(a > b)。每个大整数不超过 200 位, 不会有多余的前导零。

    输出:

    一行,即所求的差。

    样例输入 9999999999999999999999999999999999999

         9999999999999

    样例输出 9999999999999999999999990000000000000

    题目来源:http://noi.openjudge.cn/ch0106/11/

    分析:

    1、借位问题;

       for (int i=1;i<=la;i++)

      {  

         if (a[i]<b[i])

         {   

            a[i+1]--;

            a[i]+=10;

         }

          a[i]-=b[i];

       }

    2、输出时去掉前面多余的 0。 while (a[la]==0&&la>1)la--;
     
    程序实现:

    //高精度减法运算 
    #include <iostream>
    #include <cstdio>
    #include <cstring>
    using namespace std;
    
    char s1[300], s2[300], s3[300];
    int a[300], b[300];
    
    int main()
    {
    	int la, lb, m=0;
    	cin >> s1 >> s2;
    	la = strlen(s1);
    	lb = strlen(s2);
    	if(strcmp(s1, s2) == 0)
    	{
    		cout << 0;
    		return 0;
    	}
    	if(la<lb || la==lb && strcmp(s1, s2)<0 )
    	{
    		cout << "-";
    		strcpy(s3, s1);
    		strcpy(s1, s2);
    		strcpy(s2, s3);
    	}
    	la = strlen(s1);
    	lb = strlen(s2);
    	for(int i=1;i<=la;i++)
    		a[i] = s1[la-i] - 48;
    	for(int i=1;i<=lb;i++)
    		b[i] = s2[lb-i] - 48;
    	for(int i=1;i<=la;i++)
    	{
    		if(a[i] < b[i])
    		{
    			a[i+1]--;
    			a[i] += 10;
    		}
    		a[i] -= b[i];
    	}
    	
    	while(a[la] == 0 && la>1)
    		la--;
    	for(int i=la;i>=1;i--)
    		cout << a[i];
    	cout << endl;
    	
    	return 0;
    }
    

      

  • 相关阅读:
    sql查询
    PHP常用的设计模式
    PHP内存管理和垃圾回收机制
    记一次面试
    获取py文件函数名及动态调用
    正确解决 mysql 导出文件 分隔符 问题
    解决ValueError: cannot convert float NaN to integer
    Python ---接口返回值中文编码问题
    pandas python 读取大文件
    【neo4J】后台关闭后,前端还能打开视图
  • 原文地址:https://www.cnblogs.com/sineagle/p/6014414.html
Copyright © 2011-2022 走看看