栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

2021-11-16高精度(+-*/)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

2021-11-16高精度(+-*/)

高精度加法:
vector add(vector &a, vector &b)
{
      vector c;
    int temp = 0;
    for(int i=0;  i<(int)a.size() || i<(int)b.size(); i++)
    {
        if(i <(int) a.size()) temp += a[i];
        if(i <(int)b.size()) temp += b[i];
        c.push_back(temp%10);
        temp /= 10;
    }
    if(temp) c.push_back(temp);
     reverse(c.begin(), c.end());
    return c;
}
高精度减法:
#include 
#define rep(x, a, b) for(int x = a; x<=b; x++)
#define pre(x, a, b) for(int x=a; x>=b; x--)
using namespace std;
bool cmp(vector &a, vector &b)//判断数字大小
{
    if(a.size() != b.size()) return a.size()>b.size();
    for(int i=(int)a.size()-1; i>= 0; i--)
    {
        if(a[i] != b[i]) return a[i] > b[i];
    }
    return true;
}
vector sub(vector &a, vector &b)
{
      vector c;
    if(!cmp(a, b))//判断减数和被减数的大小
    {
        printf("-");//提前输出负号
        c = sub(b, a);//交换位置再次调用
        return c;
    }
    int temp = 0;
    for(int i=0;  i<(int)a.size(); i++)
    {
        temp += a[i];
        if(i < (int)b.size()) temp -= b[i];
        c.push_back((temp+10)%10);//保证压入的数字为个位正整数
        if(temp < 0) temp = -1;
        else temp = 0;
    }
    while(c.size()>1 && c.back() == 0) c.pop_back();//去除前导零

    reverse(c.begin(), c.end());//倒置
    return c;
}
高精度乘法:
vector mul(vector &a,int b)
{
    vector c;
    int temp = 0;
    for(int i=0;  i<(int)a.size(); i++)
    {
        temp += a[i]*b;
        c.push_back(temp%10);
        temp /= 10;
    }
    if(temp) c.push_back(temp);
    while(c.size()>1 && c.back() == 0) c.pop_back();
    reverse(c.begin(), c.end());
    return c;
}
高精度除法:
vector div(vector &a,int b, int &temp)
{
    vector c;
     reverse(a.begin(), a.end());
    for(int i=0;  i<(int)a.size(); i++)
    {
        temp = temp*10 + a[i];//上一位的余数*10+该位数字
        c.push_back(temp/b);//除数
        temp %= b;//注意是模b取余数
    }
    reverse(c.begin(), c.end());//倒置
    while(c.size()>1 && c.back() == 0) c.pop_back();//去前缀0
    reverse(c.begin(), c.end());//倒置回去
    return c;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/528820.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号