zoukankan      html  css  js  c++  java
  • 高精度 “加减乘除”

    加法参考代码:

    #include <iostream>
    #include <cstdio>
    #include <cmath>
    #include <string>
    #include <cstring>
    #include <algorithm>
    using namespace std;
    string add(string str1,string str2)
    {
    	string str;//用于输出最后结果
    	int len1=str1.length();
    	int len2=str2.length();
    	//前面补0,弄成长度相同;
    	if(len1>len2)
    	{
    		for(int i=1;i<=len1-len2;i++)
    			str2="0"+str2;
    	}
    	else
    	{
    		for(int i=1;i<=len2-len1;i++)
    			str1="0"+str1;
    	}
    	len1=str1.length();
    	int temp,t=0;
    	for(int i=len1-1;i>=0;i--)
    	{
    		temp=str1[i]-'0'+str2[i]-'0'+t;
    		t=temp/10;
    		temp%=10;
    		str=char(temp+'0')+str;
    	}
    	if(t!=0)
    		str=char(t+'0')+str;
    	return str;
    }
    int main()
    {
    	string str1,str2;
    	cin>>str1>>str2;
    	cout<<add(str1,str2)<<endl;
    	return 0;
    }
    

    减法参考代码:

    #include<bits/stdc++.h>
    using namespace std;
    int c[10088];
    string a,b;
    int  main()
    {
    	int aint[10088],bint[10088];
    	int j=0,k=0;
    	cin>>a;
    	cin>>b;
    	int alen=a.length();
    	int blen=b.length();
    	string temp;
    	if(alen<blen||(alen==blen&&a<b))
    	{
    		cout<<"-";
    		swap(a,b);
    		swap(alen,blen);
    	}
    	for(int i=alen-1;i>=0;i--)
    		aint[j++]=a[i]-'0';
    	for(int i=blen-1;i>=0;i--)
    		bint[k++]=b[i]-'0';
    	int maxlen=max(alen,blen);
    	if(a==b){
    		cout<<"0";
    		return 0;
    	}
    	int i=0;
    	for(i=0;i<maxlen;i++){
    		if(aint[i]<bint[i]){
    			aint[i]+=10;
    			aint[i+1]--;
    		} 
    		c[i]=aint[i]-bint[i];
    	}
    	while(c[i]==0)i--;
    	for(;i>=0;i--){
    		cout<<c[i];
    	}	
    	return 0;
    }
    
    

    高精度乘法参考代码:

    #include <iostream>
    #include <cstdio>
    #include <cmath>
    #include <string>
    #include <cstring>
    #include <algorithm>
    using namespace std;
    #define N 100000
    char a1[N],b1[N];
    int a[N],b[N],c[N],i,j,len;
    int main ()
    {
    	cin >>a1 >>b1;//读入两个数
    	a[0]=strlen(a1);b[0]=strlen(b1);//计算长度
    	for (i=1;i<=a[0];++i)
    		a[i]=a1[a[0]-i]-'0';//将字符串转换成数字
    	for (i=1;i<=b[0];++i)
    		b[i]=b1[b[0]-i]-'0';
    	for (i=1;i<=a[0];++i)
    		for (j=1;j<=b[0];++j)
    			c[i+j-1]+=a[i]*b[j];//按乘法
    	len=a[0]+b[0];//原理进行高精乘
    	for (i=1;i<len;++i)
    	{
    		if (c[i]>9)
    		{
    			c[i+1]+=c[i]/10;
    			c[i]%=10;
    		}//进位
    	}
    	while (c[len]==0&&len>1)
    		len--;//判断位数
    	for (i=len;i>=1;i--)
    		cout <<c[i];//输出
    	return 0;
    }
    
  • 相关阅读:
    MySQL锁概述
    MYSQL删除重复记录
    SPRING事务控制
    性能测试中如何确定并发用户数
    Jsoup操作
    linux根据端口号查询进程
    linux下解压jar文件
    开发阶段的logback.xml
    栈--getMin(leetcode 155)
    git "fatal: The remote end hung up unexpectedly"
  • 原文地址:https://www.cnblogs.com/yonglin1998/p/11780823.html
Copyright © 2011-2022 走看看