C++:基于高精度运算的算数表达式求解

简单地看了一下C++,趁着寒假有时间,把之前用C写的高精度算法重写了一下,而且修复了不少BUG,并且新支持了除法运算(懒得模拟竖式除法了,偷懒做了整除),现在是大半个真的高精度四则运算算法了,并且修改了之前的算数表达求解的代码,能够利用高精度运算算法计算表达式结果。
写的时候考虑的这么几点:
1.因为我把C++当作新的语言来学,所以尽量使用一些C++的东西,比如下标全部用迭代器替换
2.由于翻了翻去年十月的代码,感觉不是太好,变量名缩写的厉害,所以本代码内的变量几乎是以完整的英文单词命名,看着会有点长,但是意思不难理解,主要步骤加了注释
3.之前已经写了基于“double”运算的算数表达式求解,但是被“double”的十五位有效数字限制,感觉不爽,所以本次四则运算的函数输入输出都是“string”,方便编写基于高精度运算的算数表达式求解
4.把高精度算法和表达式求解封装在类里面,用起来更方便。

使用方法:按照下图布局,并复制对应的代码进去即可。

这里写图片描述

源.cpp:

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <Windows.h>
#include "HighPrecisionAlgorithm.h"
#include "CalculationOfArithmeticExpressions.h"

int main()
{
    HighPrecisionAlgorithm p;
    CalculationOfArithmeticExpressions *q = new CalculationOfArithmeticExpressions(p);
    q->start();
    system("pause");
}

HighPrecisionAlgorithm(高精度算法):
HighPrecisionAlgorithm.h

#pragma once
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using std::cout;
using std::cin;
using std::endl;
using std::vector;
using std::string;
class HighPrecisionAlgorithm
{
public:
    HighPrecisionAlgorithm();
    ~HighPrecisionAlgorithm();
    static string::const_iterator findDecimalPoint(const string& s);
    static string add(const string& leftOperand, const string& rightOperand);
    static string sub(const string& leftOperand, const string& rightOperand);
    static string mul(const string& leftOperand, const string& rightOperand);
    static string div(const string& leftOperand, const string& rightOperand);
    static string div(const string& leftOperand, const string& rightOperand, bool isIntegerDivision);

private:
    static bool islonger(const string& leftOperand, const string& rightOperand);//整数比较
    static bool isLonger(const string& leftOperand, const string& rightOperand);//浮点数比较
    static bool isNegativeNumber(const string& operand);//是否位负数
    static string moveMinusSign(string operand);//在开头删除负号
    static string addMinusSign(string operand);//在开头添加负号
    static string resultHandle(string operand);//处理两个负号的情况
};

HighPrecisionAlgorithm..cpp

#include "HighPrecisionAlgorithm.h"



HighPrecisionAlgorithm::HighPrecisionAlgorithm()
{
}

bool HighPrecisionAlgorithm::islonger(const string& leftOperand, const string& rightOperand)
{
    if (leftOperand.size() > rightOperand.size())
        return true;
    else
    {
        if (leftOperand.size() < rightOperand.size())
            return false;
        else
        {
            bool f = leftOperand > rightOperand;
            if (f)
                return true;
            else
            {
                return false;
            }
        }
    }
}
bool HighPrecisionAlgorithm::isLonger(const string& leftOperand, const string& rightOperand)
{
    auto litorDecimalPoint = findDecimalPoint(leftOperand);
    auto ritorDecimalPoint = findDecimalPoint(rightOperand);
    string lft1, rht1;
    auto litor = leftOperand.begin();
    auto ritor = rightOperand.begin();
    for (; litor != litorDecimalPoint; litor++)
        lft1.push_back(*litor);
    for (; ritor != ritorDecimalPoint; ritor++)
        rht1.push_back(*ritor);
    if (islonger(lft1, rht1))
        return true;
    else
    {
        if (lft1 == rht1)
        {
            string lft2, rht2;
            litor = ++litorDecimalPoint;
            ritor = ++ritorDecimalPoint;
            for (; litor != leftOperand.end(); litor++)
                lft2.push_back(*litor);
            for (; ritor != rightOperand.end(); ritor++)
                rht2.push_back(*ritor);
            return islonger(lft2, rht2);
        }
        else
        {
            return false;
        }
    }
}
bool HighPrecisionAlgorithm::isNegativeNumber(const string& operand)
{
    auto itor = operand.begin();
    if (*itor == '-')
        return true;
    else
        false;
    return false;
}
string HighPrecisionAlgorithm::moveMinusSign(string operand)
{
    auto itor = operand.begin();
    if (*itor == '-')
        operand.erase(itor);
    return operand;
}
string HighPrecisionAlgorithm::addMinusSign(string operand)
{
    operand.insert(operand.begin(), '-');
    return operand;
}
string HighPrecisionAlgorithm::resultHandle(string operand)
{
    auto itor = operand.begin();
    if (*itor == '-'&&*(itor + 1) == '-')
    {
        operand.erase(itor);
        itor = operand.begin();
        operand.erase(itor);
    }
    return operand;
}
string::const_iterator HighPrecisionAlgorithm::findDecimalPoint(const string& s)
{
    auto itor = s.begin();
    for (; itor != s.end(); itor++)
    {
        if (*itor == '.')
            return itor;
    }
    return s.begin();
}

string HighPrecisionAlgorithm::add(const string& leftOperand, const string& rightOperand)
{
    bool left = isNegativeNumber(leftOperand);
    bool right = isNegativeNumber(rightOperand);
    if (left&&right)
        return resultHandle(addMinusSign(add(moveMinusSign(leftOperand), moveMinusSign(rightOperand))));
    else
    {
        if (left && !right)
            return resultHandle(sub(rightOperand, moveMinusSign(leftOperand)));
        else
        {
            if (!left && right)
                return sub(leftOperand, moveMinusSign(rightOperand));
        }

    }
    vector<int> leftOperand_IntegralPart, rightOperand_IntegralPart;//储存整数容器
    vector<int> leftOperand_DecimalPart, rightOperand_DecimalPart;//储存小数容器
    string result;//储存结果的字符串
    bool isIntegerNumber_add = true;//是否为整数结果
    auto leftOperandIterator = leftOperand.end();
    auto rightOperandIterator = rightOperand.end();
    for (auto c : leftOperand)
    {
        if (c == '.')
            isIntegerNumber_add = false;
    }
    for (auto c : rightOperand)
    {
        if (c == '.')
            isIntegerNumber_add = false;
    }

    if (isIntegerNumber_add)
    {

        //      ********************倒序存储整数********************
        for (;leftOperandIterator> leftOperand.begin(); leftOperandIterator--)
        {
            leftOperand_IntegralPart.push_back(*(leftOperandIterator-1) - '0');
        }
        for (; rightOperandIterator > rightOperand.begin(); rightOperandIterator--)
        {
            rightOperand_IntegralPart.push_back(*(rightOperandIterator-1) - '0');
        }
        leftOperand_IntegralPart.push_back(0);//预留位数用作最高位进位
        rightOperand_IntegralPart.push_back(0);
        //      ********************倒序存储整数********************

        int sizeDifference = leftOperand_IntegralPart.size() - rightOperand_IntegralPart.size();

        //      ********************位数对齐********************
        if (sizeDifference > 0)
        {
            while (sizeDifference--)
                rightOperand_IntegralPart.push_back(0);
        }
        else
        {
            while (sizeDifference++)
                leftOperand_IntegralPart.push_back(0);
        }
        //      ********************位数对齐********************

        //      ********************计算开始********************
        auto leftOperand_IntegralPart_Iterator = leftOperand_IntegralPart.begin();
        auto rightOperand_IntegralPart_Iterator = rightOperand_IntegralPart.begin();
        for (; leftOperand_IntegralPart_Iterator < --leftOperand_IntegralPart.end();
            leftOperand_IntegralPart_Iterator++, rightOperand_IntegralPart_Iterator++)
        {
            *(leftOperand_IntegralPart_Iterator +1) += (*leftOperand_IntegralPart_Iterator + *rightOperand_IntegralPart_Iterator) / 10;
            *leftOperand_IntegralPart_Iterator = (*leftOperand_IntegralPart_Iterator + *rightOperand_IntegralPart_Iterator) % 10;
        }
        //      ********************计算结束********************

        //      ********************结果储存********************
        leftOperand_IntegralPart_Iterator = leftOperand_IntegralPart.end();
        for (; leftOperand_IntegralPart_Iterator > leftOperand_IntegralPart.begin();
            leftOperand_IntegralPart_Iterator--)
        {
            result.push_back(*(leftOperand_IntegralPart_Iterator - 1) + '0');
        }
        auto resultIterator = result.begin();
        for (; resultIterator != result.end(); resultIterator++)
        {
            if (*resultIterator != '0')
                return result;
            else
            {
                result.erase(resultIterator);
                resultIterator = result.begin();
            }
        }
        return result;
    }
    else
    {
        string pleftOperand = leftOperand;
        string prightOperand = rightOperand;
        auto leftDecimalPointIterator = findDecimalPoint(pleftOperand);
        auto rightDecimalPointIterator = findDecimalPoint(prightOperand);
        if (leftDecimalPointIterator == pleftOperand.begin())
        {
            pleftOperand.push_back('.');
            pleftOperand.push_back('0');
            leftDecimalPointIterator = findDecimalPoint(pleftOperand);
        }
        if (rightDecimalPointIterator == prightOperand.begin())
        {
            prightOperand.push_back('.');
            prightOperand.push_back('0');
            rightDecimalPointIterator = findDecimalPoint(prightOperand);
        }
        leftOperand_DecimalPart.push_back(0);//预留位数用作小数最高位进位
        rightOperand_DecimalPart.push_back(0);

        //          ********************正序存储小数部分,倒序存储整数部分********************
        auto stringLeftIterator = leftDecimalPointIterator;
        auto stringRightIterator = rightDecimalPointIterator;
        for (; stringLeftIterator > pleftOperand.begin(); stringLeftIterator--)//从小数点开始向前读取
        {
            leftOperand_IntegralPart.push_back(*(stringLeftIterator-1) - '0');
        }
        for (; stringRightIterator > prightOperand.begin(); stringRightIterator--)
        {
            rightOperand_IntegralPart.push_back(*(stringRightIterator-1) - '0');
        }
        stringLeftIterator = leftDecimalPointIterator;
        stringRightIterator = rightDecimalPointIterator;
        for (stringLeftIterator++; stringLeftIterator != pleftOperand.end(); stringLeftIterator++)//从最后读取到小数点结束
        {
            leftOperand_DecimalPart.push_back(*stringLeftIterator - '0');
        }
        for (stringRightIterator++; stringRightIterator != prightOperand.end(); stringRightIterator++)
        {
            rightOperand_DecimalPart.push_back(*stringRightIterator - '0');
        }
        leftOperand_IntegralPart.push_back(0);//预留位数用作整数最高位进位
        rightOperand_IntegralPart.push_back(0);
        //          ********************正序存储小数部分,倒序存储整数部分********************

        //          ********************储存内容位数对齐********************
        int sizeDifference = leftOperand_IntegralPart.size() - rightOperand_IntegralPart.size();
        if (sizeDifference > 0)
        {
            while (sizeDifference--)
                rightOperand_IntegralPart.push_back(0);
        }
        else
        {
            while (sizeDifference++)
                leftOperand_IntegralPart.push_back(0);
        }
        sizeDifference = leftOperand_DecimalPart.size() - rightOperand_DecimalPart.size();
        if (sizeDifference > 0)
        {
            while (sizeDifference--)
                rightOperand_DecimalPart.push_back(0);
        }
        else
        {
            while (sizeDifference++)
                leftOperand_DecimalPart.push_back(0);
        }
        //          ********************储存内容位数对齐********************

        //          ********************计算开始********************
        auto leftOperand_DecimalPart_Iterator = --leftOperand_DecimalPart.end();
        auto rightOperand_DecimalPart_Iterator = --rightOperand_DecimalPart.end();
        for (; leftOperand_DecimalPart_Iterator >= ++leftOperand_DecimalPart.begin();
            leftOperand_DecimalPart_Iterator--, rightOperand_DecimalPart_Iterator--)
        {
            *(leftOperand_DecimalPart_Iterator-1) += (*leftOperand_DecimalPart_Iterator + *rightOperand_DecimalPart_Iterator) / 10;
            *leftOperand_DecimalPart_Iterator = (*leftOperand_DecimalPart_Iterator + *rightOperand_DecimalPart_Iterator) % 10;
        }
        leftOperand_DecimalPart_Iterator = leftOperand_DecimalPart.begin();
        auto leftOperand_IntegralPart_Iterator = leftOperand_IntegralPart.begin();
        auto rightOperand_IntegralPart_Iterator = rightOperand_IntegralPart.begin();
        if (*leftOperand_DecimalPart_Iterator != 0)//小数进位处理
        {
            *leftOperand_IntegralPart_Iterator += *leftOperand_DecimalPart_Iterator;
        }
        for (; leftOperand_IntegralPart_Iterator < --leftOperand_IntegralPart.end();
            leftOperand_IntegralPart_Iterator++, rightOperand_IntegralPart_Iterator++)
        {
            *(leftOperand_IntegralPart_Iterator + 1) += (*leftOperand_IntegralPart_Iterator + *rightOperand_IntegralPart_Iterator) / 10;
            *leftOperand_IntegralPart_Iterator = (*leftOperand_IntegralPart_Iterator + *rightOperand_IntegralPart_Iterator) % 10;
        }

        //          ********************结果存储返回********************
        leftOperand_IntegralPart_Iterator = leftOperand_IntegralPart.end();
        leftOperand_DecimalPart_Iterator = ++leftOperand_DecimalPart.begin();
        for (; leftOperand_IntegralPart_Iterator > leftOperand_IntegralPart.begin();
            leftOperand_IntegralPart_Iterator--)
        {
            result.push_back(*(leftOperand_IntegralPart_Iterator - 1) + '0');
        }
        result.push_back('.');
        for (; leftOperand_DecimalPart_Iterator != leftOperand_DecimalPart.end();
            leftOperand_DecimalPart_Iterator++)
        {
            result.push_back(*leftOperand_DecimalPart_Iterator + '0');
        }
        auto resultIterator = result.begin();
        for (; resultIterator != result.end();)
        {
            if (*resultIterator != '0')
                return result;
            else
            {
                result.erase(resultIterator);
                resultIterator = result.begin();
            }
        }
        return result;
    }
    return result;
}
string HighPrecisionAlgorithm::sub(const string& leftOperand, const string& rightOperand)
{
    bool left = isNegativeNumber(leftOperand);
    bool right = isNegativeNumber(rightOperand);
    if (left&&right)
    {
        return sub(moveMinusSign(rightOperand), moveMinusSign(leftOperand));
    }
    else
    {
        if (left && !right)
            return addMinusSign(add(moveMinusSign(leftOperand), rightOperand));
        else
        {
            if (!left && right)
                return add(leftOperand, moveMinusSign(rightOperand));
        }
    }

    vector<int> leftOperand_IntegralPart, rightOperand_IntegralPart;//储存整数容器
    vector<int> leftOperand_DecimalPart, rightOperand_DecimalPart;//储存小数容器
    string result;//储存结果的字符串
    bool isIntegerNumber_sub = true;//是否为整数结果
    bool isNegativeNumber = false;//是否为负数结果
    auto leftOperandIterator = leftOperand.end();
    auto rightOperandIterator = rightOperand.end();
    for (auto c : leftOperand)
    {
        if (c == '.')
            isIntegerNumber_sub = false;
    }
    for (auto c : rightOperand)
    {
        if (c == '.')
            isIntegerNumber_sub = false;
    }
    if (isIntegerNumber_sub)
    {
        //      ********************倒序存储整数********************
        for (; leftOperandIterator > leftOperand.begin(); leftOperandIterator--)
        {
            leftOperand_IntegralPart.push_back(*(leftOperandIterator - 1) - '0');
        }
        for (; rightOperandIterator > rightOperand.begin(); rightOperandIterator--)
        {
            rightOperand_IntegralPart.push_back(*(rightOperandIterator - 1) - '0');
        }
        leftOperand_IntegralPart.push_back(0);//预留位数用作最高位进位
        rightOperand_IntegralPart.push_back(0);
        //      ********************倒序存储整数********************


        //      ********************位数对齐********************
        int sizeDifference = leftOperand_IntegralPart.size() - rightOperand_IntegralPart.size();
        if (sizeDifference > 0)
        {
            while (sizeDifference--)
                rightOperand_IntegralPart.push_back(0);
        }
        else
        {
            while (sizeDifference++)
                leftOperand_IntegralPart.push_back(0);
        }
        //      ********************位数对齐********************

        //      ********************计算开始********************
        auto leftOperand_IntegralPart_Iterator = leftOperand_IntegralPart.begin();
        auto rightOperand_IntegralPart_Iterator = rightOperand_IntegralPart.begin();
        if (islonger(leftOperand,rightOperand))
        {
            for (; leftOperand_IntegralPart_Iterator < --leftOperand_IntegralPart.end();
                leftOperand_IntegralPart_Iterator++, rightOperand_IntegralPart_Iterator++)
            {
                if (*leftOperand_IntegralPart_Iterator < *rightOperand_IntegralPart_Iterator)
                {
                    *(leftOperand_IntegralPart_Iterator + 1) -= 1;
                    *leftOperand_IntegralPart_Iterator = 10 - *rightOperand_IntegralPart_Iterator + *leftOperand_IntegralPart_Iterator;
                }
                else
                {
                    *leftOperand_IntegralPart_Iterator -= *rightOperand_IntegralPart_Iterator;
                }
            }
            //      ********************计算结束********************

            //      ********************结果储存返回********************
            leftOperand_IntegralPart_Iterator = leftOperand_IntegralPart.end();
            for (; leftOperand_IntegralPart_Iterator > leftOperand_IntegralPart.begin();
                leftOperand_IntegralPart_Iterator--)
            {
                result.push_back(*(leftOperand_IntegralPart_Iterator - 1) + '0');
            }
            auto resultIterator = result.begin();
            for (; resultIterator != result.end(); resultIterator++)
            {
                if (*resultIterator != '0')
                    return result;
                else
                {
                    result.erase(resultIterator);
                    resultIterator = result.begin();
                }
            }
            return result;
        }
        else
        {
            //      ********************计算开始********************
            for (; leftOperand_IntegralPart_Iterator < --leftOperand_IntegralPart.end();
                leftOperand_IntegralPart_Iterator++, rightOperand_IntegralPart_Iterator++)
            {
                if (*rightOperand_IntegralPart_Iterator < *leftOperand_IntegralPart_Iterator++)
                {
                    *(rightOperand_IntegralPart_Iterator + 1) -= 1;
                    *rightOperand_IntegralPart_Iterator = 10 - *leftOperand_IntegralPart_Iterator + *rightOperand_IntegralPart_Iterator;
                }
                else
                {
                    *rightOperand_IntegralPart_Iterator -= *leftOperand_IntegralPart_Iterator;
                }
            }
            //      ********************计算结束********************

            //      ********************结果储存返回********************
            rightOperand_IntegralPart_Iterator = rightOperand_IntegralPart.end();
            result.push_back('-');
            for (; rightOperand_IntegralPart_Iterator > rightOperand_IntegralPart.begin();
                rightOperand_IntegralPart_Iterator--)
            {
                result.push_back(*(rightOperand_IntegralPart_Iterator - 1) + '0');
            }
            auto resultIterator = ++result.begin();
            for (; resultIterator != result.end(); resultIterator++)
            {
                if (*resultIterator != '0')
                    return result;
                else
                {
                    result.erase(resultIterator);
                    resultIterator = result.begin();
                }
            }
            return result;
        }
        return result;
    }
    else
    {
        string pleftOperand = leftOperand;
        string prightOperand = rightOperand;
        auto leftDecimalPointIterator = findDecimalPoint(pleftOperand);
        auto rightDecimalPointIterator = findDecimalPoint(prightOperand);
        if (leftDecimalPointIterator == pleftOperand.begin())
        {
            pleftOperand.push_back('.');
            pleftOperand.push_back('0');
            leftDecimalPointIterator = findDecimalPoint(pleftOperand);
        }
        if (rightDecimalPointIterator == prightOperand.begin())
        {
            prightOperand.push_back('.');
            prightOperand.push_back('0');
            rightDecimalPointIterator = findDecimalPoint(prightOperand);
        }
        leftOperand_DecimalPart.push_back(0);//预留位数用作小数最高位进位
        rightOperand_DecimalPart.push_back(0);

        //          正序存储小数部分,倒序存储整数部分
        auto stringLeftIterator = leftDecimalPointIterator;
        auto stringRightIterator = rightDecimalPointIterator;
        for (; stringLeftIterator > pleftOperand.begin(); stringLeftIterator--)//从小数点开始向前读取
        {
            leftOperand_IntegralPart.push_back(*(stringLeftIterator - 1) - '0');
        }
        for (; stringRightIterator > prightOperand.begin(); stringRightIterator--)
        {
            rightOperand_IntegralPart.push_back(*(stringRightIterator - 1) - '0');
        }
        stringLeftIterator = leftDecimalPointIterator;
        stringRightIterator = rightDecimalPointIterator;
        for (stringLeftIterator++; stringLeftIterator != pleftOperand.end(); stringLeftIterator++)//从最后读取到小数点结束
        {
            leftOperand_DecimalPart.push_back(*stringLeftIterator - '0');
        }
        for (stringRightIterator++; stringRightIterator != prightOperand.end(); stringRightIterator++)
        {
            rightOperand_DecimalPart.push_back(*stringRightIterator - '0');
        }
        leftOperand_IntegralPart.push_back(0);//预留位数用作整数最高位进位
        rightOperand_IntegralPart.push_back(0);

        //          ********************储存内容位数对齐********************
        int sizeDifference = leftOperand_IntegralPart.size() - rightOperand_IntegralPart.size();
        if (sizeDifference > 0)
        {
            while (sizeDifference--)
                rightOperand_IntegralPart.push_back(0);
        }
        else
        {
            while (sizeDifference++)
                leftOperand_IntegralPart.push_back(0);
        }
        sizeDifference = leftOperand_DecimalPart.size() - rightOperand_DecimalPart.size();
        if (sizeDifference > 0)
        {
            while (sizeDifference--)
                rightOperand_DecimalPart.push_back(0);
        }
        else
        {
            while (sizeDifference++)
                leftOperand_DecimalPart.push_back(0);
        }
        //          ********************储存内容位数对齐********************

        //          ********************计算开始********************
        auto leftOperand_DecimalPart_Iterator = --leftOperand_DecimalPart.end();
        auto rightOperand_DecimalPart_Iterator = --rightOperand_DecimalPart.end();
        if (isLonger(leftOperand,rightOperand))
        {
            for (; leftOperand_DecimalPart_Iterator >= ++leftOperand_DecimalPart.begin();
                leftOperand_DecimalPart_Iterator--, rightOperand_DecimalPart_Iterator--)
            {
                if (*leftOperand_DecimalPart_Iterator < *rightOperand_DecimalPart_Iterator)
                {
                    *(leftOperand_DecimalPart_Iterator - 1) -= 1;
                    *leftOperand_DecimalPart_Iterator = 10 - *rightOperand_DecimalPart_Iterator + *leftOperand_DecimalPart_Iterator;
                }
                else
                {
                    *leftOperand_DecimalPart_Iterator -= *rightOperand_DecimalPart_Iterator;
                }
            }
            leftOperand_DecimalPart_Iterator = leftOperand_DecimalPart.begin();
            auto leftOperand_IntegralPart_Iterator = leftOperand_IntegralPart.begin();
            auto rightOperand_IntegralPart_Iterator = rightOperand_IntegralPart.begin();
            if (*leftOperand_DecimalPart_Iterator != 0)//小数进位处理
            {
                *leftOperand_IntegralPart_Iterator += *leftOperand_DecimalPart_Iterator;
            }
            for (; leftOperand_IntegralPart_Iterator < --leftOperand_IntegralPart.end();
                leftOperand_IntegralPart_Iterator++, rightOperand_IntegralPart_Iterator++)
            {
                if (*leftOperand_IntegralPart_Iterator < *rightOperand_IntegralPart_Iterator)
                {
                    *(leftOperand_IntegralPart_Iterator + 1) -= 1;
                    *leftOperand_IntegralPart_Iterator = 10 - *rightOperand_IntegralPart_Iterator + *leftOperand_IntegralPart_Iterator;
                }
                else
                {
                    *leftOperand_IntegralPart_Iterator -= *rightOperand_IntegralPart_Iterator;
                }
            }
            //          ********************计算结束********************

            //          ********************结果存储返回********************
            leftOperand_IntegralPart_Iterator = leftOperand_IntegralPart.end();
            leftOperand_DecimalPart_Iterator = ++leftOperand_DecimalPart.begin();
            for (; leftOperand_IntegralPart_Iterator > leftOperand_IntegralPart.begin();
                leftOperand_IntegralPart_Iterator--)
            {
                result.push_back(*(leftOperand_IntegralPart_Iterator - 1) + '0');
            }
            result.push_back('.');
            for (; leftOperand_DecimalPart_Iterator != leftOperand_DecimalPart.end();
                leftOperand_DecimalPart_Iterator++)
            {
                result.push_back(*leftOperand_DecimalPart_Iterator + '0');
            }
            auto resultIterator = result.begin();
            //for (; resultIterator != result.end(); resultIterator++)
            for (; resultIterator != result.end();)
            {
                if (*resultIterator != '0')
                    return result;
                else
                {
                    result.erase(resultIterator);
                    resultIterator = result.begin();
                }
            }
            return result;
        }
        else
        {
            //          ********************计算开始********************
            for (; rightOperand_DecimalPart_Iterator >= ++rightOperand_DecimalPart.begin();
                rightOperand_DecimalPart_Iterator--, leftOperand_DecimalPart_Iterator--)
            {
                if (*rightOperand_DecimalPart_Iterator < *leftOperand_DecimalPart_Iterator)
                {
                    *(rightOperand_DecimalPart_Iterator - 1) -= 1;leftOperand_DecimalPart_Iterator + *rightOperand_DecimalPart_Iterator;
                }
                else
                {
                    *rightOperand_DecimalPart_Iterator -= *leftOperand_DecimalPart_Iterator;
                }
            }
            rightOperand_DecimalPart_Iterator = rightOperand_DecimalPart.begin();
            auto rightOperand_IntegralPart_Iterator = rightOperand_IntegralPart.begin();
            auto leftOperand_IntegralPart_Iterator = leftOperand_IntegralPart.begin();
            if (*rightOperand_DecimalPart_Iterator != 0)//小数进位处理
            {
                *rightOperand_IntegralPart_Iterator += *rightOperand_DecimalPart_Iterator;
            }
            for (; rightOperand_IntegralPart_Iterator < --rightOperand_IntegralPart.end();
                rightOperand_IntegralPart_Iterator++, leftOperand_IntegralPart_Iterator++)
            {
                if (*rightOperand_IntegralPart_Iterator < *leftOperand_IntegralPart_Iterator)
                {
                    *(rightOperand_IntegralPart_Iterator + 1) -= 1;
                    *rightOperand_IntegralPart_Iterator = 10 - *leftOperand_IntegralPart_Iterator + *rightOperand_IntegralPart_Iterator;
                }
                else
                {
                    *rightOperand_IntegralPart_Iterator -= *leftOperand_IntegralPart_Iterator;
                }
            }
            //          ********************计算结束********************

            //          ********************结果存储返回********************
            result.push_back('-');
            rightOperand_IntegralPart_Iterator = rightOperand_IntegralPart.end();
            rightOperand_DecimalPart_Iterator = ++rightOperand_DecimalPart.begin();
            for (; rightOperand_IntegralPart_Iterator > rightOperand_IntegralPart.begin();
                rightOperand_IntegralPart_Iterator--)
            {
                result.push_back(*(rightOperand_IntegralPart_Iterator - 1) + '0');
            }
            result.push_back('.');
            for (; rightOperand_DecimalPart_Iterator != rightOperand_DecimalPart.end();
                rightOperand_DecimalPart_Iterator++)
            {
                result.push_back(*rightOperand_DecimalPart_Iterator + '0');
            }
            auto resultIterator = ++result.begin();
            for (; resultIterator != result.end(); resultIterator++)
            {
                if (*resultIterator != '0')
                    return result;
                else
                {
                    if (*(resultIterator + 1) != '.')
                    {
                        result.erase(resultIterator);
                        resultIterator = result.begin();
                    }
                    else
                        return result;
                }
            }
            return result;
        }

    }
}
string HighPrecisionAlgorithm::mul(const string& leftOperand, const string& rightOperand)
{
    bool left = isNegativeNumber(leftOperand);
    bool right = isNegativeNumber(rightOperand);
    bool isNegativeNumber_mul = false;//是否为负数结果
    if (left&&right)
        isNegativeNumber_mul = false;
    else
    {
        if (left && !right)
            isNegativeNumber_mul = true;
        else
        {
            if (!left && right)
                isNegativeNumber_mul = true;
        }
    }

    {
        string left = leftOperand, right = rightOperand;
        string leftOperand = moveMinusSign(left);//用局部变量覆盖参数
        string rightOperand = moveMinusSign(right);
        auto leftDecimalPointIterator = findDecimalPoint(leftOperand);
        auto rightDecimalPointIterator = findDecimalPoint(rightOperand);
        if (leftDecimalPointIterator == leftOperand.begin())
        {
            leftOperand.push_back('.');
            leftOperand.push_back('0');
            leftDecimalPointIterator = findDecimalPoint(leftOperand);
        }
        if (rightDecimalPointIterator == rightOperand.begin())
        {
            rightOperand.push_back('.');
            rightOperand.push_back('0');
            rightDecimalPointIterator = findDecimalPoint(rightOperand);
        }

        vector<int> leftOperand_IntegralPart, rightOperand_IntegralPart;//储存整数容器
        vector<int> tempResult;
        string result;//储存结果的字符串
        bool isIntegerNumber_mul = true;//是否为整数结果
        unsigned long long resultSize;
        auto leftOperandIterator = leftOperand.end();
        auto rightOperandIterator = rightOperand.end();
        auto tempResult_Iterator = tempResult.begin();
        for (auto c : leftOperand)
        {
            if (c == '.')
                isIntegerNumber_mul = false;
        }
        for (auto c : rightOperand)
        {
            if (c == '.')
                isIntegerNumber_mul = false;
        }

        //      倒序存储整数

        for (; leftOperandIterator > leftOperand.begin(); leftOperandIterator--)
        {
            if (*(leftOperandIterator - 1) != '.')
                leftOperand_IntegralPart.push_back(*(leftOperandIterator - 1) - '0');
        }
        for (; rightOperandIterator > rightOperand.begin(); rightOperandIterator--)
        {
            if (*(rightOperandIterator - 1) != '.')
                rightOperand_IntegralPart.push_back(*(rightOperandIterator - 1) - '0');
        }
        resultSize = static_cast<unsigned long long>(rightOperand_IntegralPart.size() + leftOperand_IntegralPart.size());
        for (int i = 0; i <= resultSize; i++)
        {
            tempResult.push_back(0);
        }


        //      ********************计算开始********************
        auto leftOperand_IntegralPart_Iterator = leftOperand_IntegralPart.begin();
        auto rightOperand_IntegralPart_Iterator = rightOperand_IntegralPart.begin();
        for (int i = 0; leftOperand_IntegralPart_Iterator != leftOperand_IntegralPart.end(); leftOperand_IntegralPart_Iterator++, i++)
        {
            tempResult_Iterator = tempResult.begin();
            for (; rightOperand_IntegralPart_Iterator != rightOperand_IntegralPart.end(); rightOperand_IntegralPart_Iterator++, tempResult_Iterator++)
            {
                *(tempResult_Iterator + i) += *leftOperand_IntegralPart_Iterator * *rightOperand_IntegralPart_Iterator;
            }
            rightOperand_IntegralPart_Iterator = rightOperand_IntegralPart.begin();
        }

        tempResult_Iterator = tempResult.begin();
        for (; tempResult_Iterator < --tempResult.end(); tempResult_Iterator++)//进位处理
        {
            *(tempResult_Iterator + 1) += *tempResult_Iterator / 10;
            *tempResult_Iterator %= 10;
        }
        tempResult_Iterator = --tempResult.end();
        for (; tempResult_Iterator > tempResult.begin(); tempResult_Iterator--)//删除多余的0
        {
            if (*tempResult_Iterator == 0)
            {
                tempResult.erase(tempResult_Iterator);
                tempResult_Iterator = tempResult.end();
            }
            else
                break;
        }

        //      ********************计算结束********************

        //      ********************结果储存返回********************
        if (isIntegerNumber_mul)
        {
            tempResult_Iterator = tempResult.end();
            for (; tempResult_Iterator > tempResult.begin();
                tempResult_Iterator--)
            {
                result.push_back(*(tempResult_Iterator - 1) + '0');
            }
            auto resultIterator = result.begin();
            for (; resultIterator != result.end();)
            {
                if (*resultIterator != '0')
                {
                    if (isNegativeNumber_mul)
                        result.insert(result.begin(), '-');
                    return result;
                }
                else
                {
                    result.erase(resultIterator);
                    resultIterator = result.begin();
                }
            }
            if (isNegativeNumber_mul)
                result.insert(result.begin(), '-');
            return result;
        }
        else
        {
            string pleftOperand = leftOperand;
            string prightOperand = rightOperand;
            auto leftDecimalPointIterator = findDecimalPoint(pleftOperand);
            auto rightDecimalPointIterator = findDecimalPoint(prightOperand);
            if (leftDecimalPointIterator == pleftOperand.begin())
            {
                pleftOperand.push_back('.');
                pleftOperand.push_back('0');
                leftDecimalPointIterator = findDecimalPoint(pleftOperand);
            }
            if (rightDecimalPointIterator == prightOperand.begin())
            {
                prightOperand.push_back('.');
                prightOperand.push_back('0');
                rightDecimalPointIterator = findDecimalPoint(prightOperand);
            }

            //      定位小数位置,用于后续得到计算结果的小数点的位置
            auto leftOperand_DecimalPoint_PositionDifference = pleftOperand.end() - leftDecimalPointIterator - 1;
            auto rightOperand_DecimalPoint_PositionDifference = prightOperand.end() - rightDecimalPointIterator - 1;

            tempResult_Iterator = tempResult.begin();
            for (int i = 0; tempResult_Iterator != tempResult.end();
                tempResult_Iterator++, i++)
            {
                if (i != leftOperand_DecimalPoint_PositionDifference + rightOperand_DecimalPoint_PositionDifference)//如果当前位置不是小数点的位置
                    result.push_back(*tempResult_Iterator + '0');
                else
                {
                    result.push_back('.');
                    tempResult_Iterator--;
                }
            }
            std::reverse(result.begin(), result.end());//反转字符串
            auto resultIterator = result.begin();
            for (; resultIterator != result.end();)
            {
                if (*resultIterator != '0')
                {
                    if (isNegativeNumber_mul)
                        result.insert(result.begin(), '-');
                    return result;
                }
                else
                {
                    if (*(resultIterator + 1) != '.')
                    {
                        result.erase(resultIterator);
                        resultIterator = result.begin();
                    }
                    else
                    {
                        if (isNegativeNumber_mul)
                            result.insert(result.begin(), '-');
                        return result;
                    }
                }
            }
            if (isNegativeNumber_mul)
                result.insert(result.begin(), '-');
            return result;
        }
    }
}
string HighPrecisionAlgorithm::div(const string& leftOperand, const string& rightOperand)
{
    bool left = isNegativeNumber(leftOperand);
    bool right = isNegativeNumber(rightOperand);
    bool isNegativeNumber_div = false;//是否为负数结果
    if (left&&right)
        isNegativeNumber_div = false;
    else
    {
        if (left && !right)
            isNegativeNumber_div = true;
        else
        {
            if(!left&&right)
                isNegativeNumber_div = true;
        }
    }

    string i = "0";
    string result;
    string quotient_IntegralPart = leftOperand;
    string quotient_DecimalPart = rightOperand;
    if (findDecimalPoint(quotient_IntegralPart) == quotient_IntegralPart.begin())
    {
        quotient_IntegralPart.push_back('.');
        quotient_IntegralPart.push_back('0');
    }
    if (findDecimalPoint(quotient_DecimalPart) == quotient_DecimalPart.begin())
    {
        quotient_DecimalPart.push_back('.');
        quotient_DecimalPart.push_back('0');
    }
    if (left)
        quotient_IntegralPart.erase(quotient_IntegralPart.begin());
    if (right)
        quotient_DecimalPart.erase(quotient_DecimalPart.begin());


    while (isLonger(quotient_IntegralPart, quotient_DecimalPart))
    {
        quotient_IntegralPart = sub(quotient_IntegralPart, quotient_DecimalPart);
        i = add(i, "1");
    }
    if (isNegativeNumber_div)
        result = '-' + i + "······" + quotient_IntegralPart;
    else
        result = i + "······" + quotient_IntegralPart;
    return result;
}
string HighPrecisionAlgorithm::div(const string& leftOperand, const string& rightOperand,bool isIntegerDivision)
{
    bool left = isNegativeNumber(leftOperand);
    bool right = isNegativeNumber(rightOperand);
    bool isNegativeNumber_div = false;//是否为负数结果
    if (left&&right)
        isNegativeNumber_div = false;
    else
    {
        if (left && !right)
            isNegativeNumber_div = true;
        else
        {
            if (!left&&right)
                isNegativeNumber_div = true;
        }
    }

    string i = "0";
    string result;
    string quotient_IntegralPart = leftOperand;
    string quotient_DecimalPart = rightOperand;
    if (findDecimalPoint(quotient_IntegralPart) == quotient_IntegralPart.begin())
    {
        quotient_IntegralPart.push_back('.');
        quotient_IntegralPart.push_back('0');
    }
    if (findDecimalPoint(quotient_DecimalPart) == quotient_DecimalPart.begin())
    {
        quotient_DecimalPart.push_back('.');
        quotient_DecimalPart.push_back('0');
    }
    if (left)
        quotient_IntegralPart.erase(quotient_IntegralPart.begin());
    if (right)
        quotient_DecimalPart.erase(quotient_DecimalPart.begin());


    while (isLonger(quotient_IntegralPart, quotient_DecimalPart))
    {
        quotient_IntegralPart = sub(quotient_IntegralPart, quotient_DecimalPart);
        i = add(i, "1");
    }
    if (isNegativeNumber_div)
        result = '-' + i;
    else
        result = i;
    return result;
}


HighPrecisionAlgorithm::~HighPrecisionAlgorithm()
{
}

CalculationOfArithmeticExpressions(算数表达式求解):

CalculationOfArithmeticExpressions.h

#pragma once
#include <stack>
#include "HighPrecisionAlgorithm.h"

using std::stack;

typedef struct binary_tree
{
    string data;
    struct binary_tree *leftTree;
    struct binary_tree *rightTree;
}tree;

class CalculationOfArithmeticExpressions
{
public:
    CalculationOfArithmeticExpressions(const HighPrecisionAlgorithm& HPA);
    void start();
    ~CalculationOfArithmeticExpressions();
private:
    tree* head;
    stack<string> stack_polishNotation;
    stack<string> stack_result;
    const HighPrecisionAlgorithm& HPA;
    string getNumber(const string& expression, string::const_iterator first, string::const_iterator last);
    void Preorder_traversal(const tree* head);
    string getResult();
    tree* buildBinary_tree(const string& expression, string::const_iterator first, string::const_iterator last);
};

CalculationOfArithmeticExpressions.cpp

#include "CalculationOfArithmeticExpressions.h"



CalculationOfArithmeticExpressions::CalculationOfArithmeticExpressions(const HighPrecisionAlgorithm& HPA)
    :HPA(HPA) {}
CalculationOfArithmeticExpressions::~CalculationOfArithmeticExpressions()
{
}

string CalculationOfArithmeticExpressions::getNumber(const string& expression, string::const_iterator first, string::const_iterator last)
{
    for (auto i = first; i != last; i++)
    {
        if (*i == '+' || *i == '-' || *i == '*' || *i == '/' || *i == '(' || *i == ')')
            return "NULL";
    }
    string s;
    for (; first != last; first++)
        s.push_back(*first);
    return s;
}

void CalculationOfArithmeticExpressions::start()
{
    string s;
    std::cin >> s;
    head = buildBinary_tree(s, s.begin(), s.end());
    Preorder_traversal(head);
    cout << "结果为: "<<getResult() << endl;
}
void CalculationOfArithmeticExpressions::Preorder_traversal(const tree* head)
{
    if (head)
    {
        stack_polishNotation.push(head->data);//通过栈将波兰式转化为逆波兰式
        Preorder_traversal(head->leftTree);
        Preorder_traversal(head->rightTree);
    }
}
string CalculationOfArithmeticExpressions::getResult()
{
    string number, leftOperand, rightOperand;
    while (!stack_polishNotation.empty())
    {
        number = stack_polishNotation.top();
        stack_polishNotation.pop();
        if (number == "+" || number == "-" || number == "*" || number == "/")
        {
            leftOperand = stack_result.top();
            stack_result.pop();
            rightOperand = stack_result.top();
            stack_result.pop();
            switch (*number.begin())
            {
            case '+':stack_result.push(HPA.add(leftOperand, rightOperand)); break;
            case '-':stack_result.push(HPA.sub(leftOperand, rightOperand)); break;
            case '*':stack_result.push(HPA.mul(leftOperand, rightOperand)); break;
            case '/':stack_result.push(HPA.div(leftOperand, rightOperand, true)); break;
            }
        }
        else
        {
            stack_result.push(number);
        }
    }
    return stack_result.top();
}
tree* CalculationOfArithmeticExpressions::buildBinary_tree(const string& expression, string::const_iterator first, string::const_iterator last)
{
    string s = getNumber(expression, first, last);
    if (s != "NULL")
    {
        tree *bn = new tree();
        bn->data = s;
        bn->leftTree = NULL;
        bn->rightTree = NULL;
        return bn;
    }
    int flag = 0;
    auto addPossition = expression.end();
    auto mulPossition = expression.end();
    auto operator_IteratorPossition = expression.end();
    for (auto i = first; i != last; i++)
    {
        if (*i == '(')
            flag++;
        if (*i == ')')
            flag--;
        if (flag == 0)//如果在括号外
        {
            if (*i == '+' || *i == '-')
                addPossition = i;
            if (*i == '*' || *i == '/')
                mulPossition = i;
        }
    }
    if (addPossition == expression.end() && mulPossition == expression.end())
        buildBinary_tree(expression, first + 1, last - 1);
    else
    {
        if (addPossition != expression.end())
            operator_IteratorPossition = addPossition;
        else
        {
            if (mulPossition != expression.end())
                operator_IteratorPossition = mulPossition;
        }
        tree *p = new tree();
        p->data = *operator_IteratorPossition;
        p->leftTree = buildBinary_tree(expression, first, operator_IteratorPossition);//重新定义递归参数,传递运算符左边的表达式建立左树
        p->rightTree = buildBinary_tree(expression, operator_IteratorPossition + 1, last);//重新定义递归参数,传递运算符右边的表达式建立右树
        return p;
    }

}

猜你喜欢

转载自blog.csdn.net/kongming07/article/details/79134935