簡體   English   中英

C ++多項式加法

[英]C++ Polynomial addition

我試圖在C ++中添加兩個多項式,但我什至不知道從哪里開始。 因此,用戶可以輸入多項式的值,而不必按順序輸入或輸入任何值。

例如,可以是:多邊形1:2x ^ 5 + 5x ^ 2-2x + 9多邊形2:x ^ 2 + 0

我將系數和指數存儲在類(對象)專用字段中。 那么,我會看看Poly 1中的第一個指數嗎,首先在Poly 2中搜索相同的指數,如果找到,則添加它們? 然后繼續第二學期?

要求的代碼:(注意:目前的實現是錯誤的,我需要有關如何解決此問題的幫助。)

#include <cmath>
#include <iostream>
using namespace std;

class polynomial
{
public:
polynomial();
polynomial(int);
polynomial(int exponent[], int coefficient[], int);
~polynomial();
polynomial &operator = (const polynomial &obj);
int evaluate(double uservalue);
polynomial operator+(const polynomial &obj) const;
void operator-(const polynomial &obj) const;
void operator*(const polynomial &obj) const;
friend istream & operator>> (istream & in, polynomial &obj);
friend ostream & operator<< (ostream & out, const polynomial &obj);
friend void growone(polynomial &obj);
private:
int *coefficient;
int *exponent;
int size;
};

並執行

polynomial polynomial::operator+(const polynomial &obj) const
{
    bool matchFound = false;
    polynomial tmp;
    if (size >= obj.size) {
        for (int i = 0; i < size; i++) {
            if (i >= tmp.size) {
                growone(tmp);
            }
            for(int y = 0; i < obj.size; i++) {
                if (exponent[i] == obj.exponent[y]) {
                    tmp.coefficient[i] = (coefficient[i]+obj.coefficient[y]);
                    tmp.exponent[i] = exponent[i];
                    tmp.size++;
                    matchFound = true;
                }
            }
            if (matchFound == false) {
                tmp.coefficient[i] = coefficient[i];
                tmp.exponent[i] = exponent[i];
                tmp.size++;
            }
            matchFound = false;
        }
    } else {



    }
    return tmp;
}

您並沒有真正充分利用C ++的功能。 一個好的規則是,如果對任何東西都使用非智能指針,則應該退后一步,重新思考一下。

大量有關堆棧溢出C的問題與指針問題無關:-)並非偶然

我要補充的另一點是,實際上值得浪費少量的內存來大大簡化代碼。 這樣,我的意思是不要嘗試創建稀疏數組來保存您的項(系數-指數對)。 取而代之的是,讓每個表達式最多保留每一項,並將未使用的項的系數簡單地設置為零。 除非您有類似4x 99999999999999 + 3的表達式,否則占用的額外內存量可能是值得的。

為此,我建議僅對從零指數開始的系數使用std::vector 指數實際上是由向量中的位置決定的。 所以表達式4x 9 - 17x 3 + 3將被存儲為矢量:

{3, 0, 0, -17, 0, 0, 0, 0, 0, 4}
 0 <------- exponent -------> 9

實際上,由於系數都很好地排列在一起,因此使多項式相加和相減的任務非常容易。


因此,考慮到這一點,讓我們介紹一個簡化的類以顯示其完成方式:

#include <iostream>
#include <vector>

using std::cout;
using std::vector;
using std::ostream;

class Polynomial {
public:
    Polynomial();
    Polynomial(size_t expon[], int coeff[], size_t sz);
    ~Polynomial();
    Polynomial &operator=(const Polynomial &poly);
    Polynomial operator+(const Polynomial &poly) const;
    friend ostream &operator<<(ostream &os, const Polynomial &poly);
private:
    std::vector<int> m_coeff;
};

默認的構造函數(和析構函數)非常簡單,我們只需確保初始化的多項式始終具有至少一項:

Polynomial::Polynomial() { m_coeff.push_back(0); }
Polynomial::~Polynomial() {}

數組構造函數稍微復雜一點,因為我們希望盡早將用戶的“一切”格式轉換為易於使用的格式:

Polynomial::Polynomial(size_t expon[], int coeff[], size_t sz) {
    // Work out largest exponent and size vector accordingly.

    auto maxExpon = 0;
    for (size_t i = 0; i < sz; ++i) {
        if (expon[i] > maxExpon) {
            maxExpon = expon[i];
        }
    }
    m_coeff.resize(maxExpon + 1, 0);

    // Fill in coefficients.

    for (size_t i = 0; i < sz; ++i) {
        m_coeff[expon[i]] = coeff[i];
    }
}

現在,您將了解為什么我們決定不使用稀疏數組,並將零指數放在向量的開頭。 operator=operator+都很簡單,因為它們已經知道所有術語在哪里:

Polynomial &Polynomial::operator=(const Polynomial &poly) {
    if (this != &poly) {
        m_coeff.clear();
        for (int coeff: poly.m_coeff) {
            m_coeff.push_back(coeff);
        }
    }
    return *this;
}

Polynomial Polynomial::operator+(const Polynomial &poly) const {
    // Create sum with required size.

    size_t thisSize = this->m_coeff.size();
    size_t polySize = poly.m_coeff.size();

    Polynomial sum;
    if (thisSize > polySize) {
        sum.m_coeff.resize(thisSize, 0);
    } else {
        sum.m_coeff.resize(polySize, 0);
    }

    // Do the actual sum (ignoring terms beyond each limit).

    for (size_t idx = 0; idx < sum.m_coeff.size(); ++idx) {
        if (idx < thisSize) sum.m_coeff[idx] += this->m_coeff[idx];
        if (idx < polySize) sum.m_coeff[idx] += poly.m_coeff[idx];
    }

    return sum;
}

現在,我們只需要使用輸出功能和一條小的測試主線來完成此操作:

ostream &operator<< (ostream &os, const Polynomial &poly) {
    bool firstTerm = true;
    if (poly.m_coeff.size() == 1 && poly.m_coeff[0] == 0) {
        os << "0";
        return os;
    }

    for (size_t idx = poly.m_coeff.size(); idx > 0; --idx) {
        if (poly.m_coeff[idx - 1] != 0) {
            if (firstTerm) {
                os << poly.m_coeff[idx - 1];
            } else if (poly.m_coeff[idx - 1] == 1) {
                os << " + ";
                if (idx == 1) {
                    os << poly.m_coeff[idx - 1];
                }
            } else if (poly.m_coeff[idx - 1] == -1) {
                os << " - ";
            } else if (poly.m_coeff[idx - 1] < 0) {
                os << " - " << -poly.m_coeff[idx - 1];
            } else {
                os << " + " << poly.m_coeff[idx - 1];
            }
            if (idx > 1) {
                os << "x";
                if (idx > 2) {
                    os << "^" << idx - 1;
                }
            }
            firstTerm = false;
        }
    }
    return os;
}

int main() {
    int    c1[] = {1, 2, 3, 4, 5};
    size_t e1[] = {3, 1, 4, 0, 9};
    Polynomial p1(e1, c1, (size_t)5);
    cout << "Polynomial 1 is " << p1 << " (p1)\n";

    int    c2[] = {6, 7, 8};
    size_t e2[] = {3, 7, 9};
    Polynomial p2(e2, c2, (size_t)3);
    cout << "Polynomial 2 is " << p2 << " (p2)\n";

    Polynomial p3 = p1 + p2;
    cout << "Polynomial 3 is " << p3 << " (p3 = p1 = p2);
}

我對輸出進行了稍微重新格式化以顯示類似的術語,並將其顯示為實際操作:

Polynomial 1 is   5x^9 +        3x^4 +  x^3 + 2x + 4
Polynomial 2 is   8x^9 + 7x^7 +        6x^3
                 ===================================
Polynomial 3 is  13x^9 + 7x^7 + 3x^4 + 7x^3 + 2x + 4

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM