带有多项式的 C++ 方程

Posted

技术标签:

【中文标题】带有多项式的 C++ 方程【英文标题】:C++ Equations with Polynomials 【发布时间】:2014-05-08 02:11:21 【问题描述】:

我在处理自己为自己制作的项目时遇到了问题。我对 C++ 和一般编程相当缺乏经验,所以我的代码可能不是最优雅或最有效的。目标是将从文件中读取的两个多项式相加、相减或相乘。这些方程的数量未知,但现在我正在处理一个。

方程的形式为 (2*x^2+3*x^4+5*x+6)+(1*x^5+4*x^2+7*x)。李> 这是我用于测试的方程式。 程序正在输出 6x^2+6x+2x^2+3x。

我今天已经为此工作了一段时间,但我似乎无法找到问题所在。我的主要问题是程序不会输出正确的答案,即使它的第一项是正确的。我知道你们不喜欢代码转储,但我不确定我们还能如何找到问题。谢谢你的帮助。

    string multiplication(double polyArray0[MAX_SIZE][2], double polyArray1[MAX_SIZE][2], int counter = 0, int iteration = 0)
    
        int updated = (counter + 1);
        string line;

        for(int i = 0; i < counter; ++i)
        
            for(int n = 0; n < iteration; ++n)
            
                polyArray0[i][0] *= polyArray1[n][0];
                polyArray0[i][1] += polyArray1[n][1];
            
        

        line = counter;

        for(int i = 0; i < counter; ++i)
        
            line += polyArray0[updated][0];
            line += polyArray0[updated][1];
        

        return line;
    

    string addition(double polyArray0[MAX_SIZE][2], double polyArray1[MAX_SIZE][2], int counter = 0, int iteration = 0)
    
        double polyArray2[MAX_SIZE][2];
        int updated = 0;
        bool additionTo;
        string line;

        for(int i = 0; i < counter; ++i)
        
            additionTo = false;

            for(int n = 0; n < iteration; ++n)
            
                if(polyArray0[i][1] == polyArray1[n][1])
                
                    polyArray0[i][0] += polyArray1[n][0];
                    additionTo = true;
                
            

            if(!additionTo)
            
                polyArray2[updated][0] = polyArray0[i][0];
                polyArray2[updated][1] = polyArray0[i][1];
                ++updated;
            
        

        line = static_cast<ostringstream*>(&(ostringstream() << (updated + counter)))->str();

        for(int i = 0; i < counter; ++i)
        
            line += static_cast<ostringstream*>(&(ostringstream() << polyArray0[i][0]))->str();
            line += static_cast<ostringstream*>(&(ostringstream() << polyArray0[i][1]))->str();
        

        for(int i = 0; i < updated; ++i)
        
            line += static_cast<ostringstream*>(&(ostringstream() << polyArray2[i][0]))->str();
            line += static_cast<ostringstream*>(&(ostringstream() << polyArray2[i][1]))->str();
        

        return line;
    

    string subtraction(double polyArray0[MAX_SIZE][2], double polyArray1[MAX_SIZE][2], int counter = 0, int iteration = 0)
    
        double polyArray2[MAX_SIZE][2];
        int updated = counter;
        string line;
        bool additionTo;

        for(int i = 0; i < iteration; ++i)
        
            polyArray1[i][0] *= -1;
        

        for(int i = 0; i < counter; ++i)
        
            additionTo = false;

            for(int n = 0; n < iteration; ++n)
            
                if(polyArray0[i][1] == polyArray1[n][1])
                
                    polyArray0[i][0] += polyArray1[n][0];
                    additionTo = true;
                
            

            if(!additionTo)
            
                polyArray2[updated][0] = polyArray0[i][0];
                polyArray2[updated][1] = polyArray1[i][1];
                ++updated;
            
        

        line = static_cast<ostringstream*>(&(ostringstream() << (updated + counter)))->str();

        for(int i = 0; i < counter; ++i)
        
            line += static_cast<ostringstream*>(&(ostringstream() << polyArray0[i][0]))->str();
            line += static_cast<ostringstream*>(&(ostringstream() << polyArray0[i][1]))->str();
        

        for(int i = 0; i < updated; ++i)
        
            line += static_cast<ostringstream*>(&(ostringstream() << polyArray2[i][0]))->str();
            line += static_cast<ostringstream*>(&(ostringstream() << polyArray2[i][1]))->str();
        

        return line;
    
int main()

    //
    // Variables :
    //  polyArray0 : used to store the left side of the equation
    //  polyArray1 : used to store the right side of the equation
    //  updated    : a counter used to ensure that the bounds of the arrays are not being overstepped
    //  counter    : a counter to find the length of a polynomial
    //  iteration  : see updated
    //  startPosition/endPosition : used to find the length of each polynomial inside of the parenthesis
    //  number     : number being converted into the array
    //  newPolynomial : will store the answer in a string
    //  polyInfo   : the string contained within the file
    //  add        : check to see if the program will be using the addition function
    //  subtract   : check to see if the program will be using the subtraction function
    //  multiply   : check to see if the program will be using the multiplication function
    //
    double polyArray0[MAX_SIZE][2];
    double polyArray1[MAX_SIZE][2];
    double updated;
    int counter = 0;
    int iteration = 0;
    int startPosition;
    int endPosition;
    string number;
    string newPolynomial;
    string polyInfo;
    string polynomial0;
    string polynomial1;
    string polynomial2;
    bool polynomial;
    bool adding;
    bool subtracting;
    bool multiplying;

    //
    // This will read in file. The file must be located in the same folder as the .cpp file.
    //
    ifstream polyFile;
    polyFile.open("functions.txt");

    //
    // Use an if statement to make sure the file is opened and then retrieve the information and store it
    // in a string called "polyFile."
    //
    if(polyFile.good())
    
        getline(polyFile, polyInfo);
    

    else
    
        cout << "The file could not be open." << endl;
    

    polynomial = true;

    //
    // Use a for loop to search through the string and find the math operator located
    // between ")" and "(."
    //
    for(int i = 0; i < polyInfo.length(); ++i)
    
        if(polyInfo.substr(i, 1) == "(")
        
            startPosition = (i + 1);
        

        else if(polyInfo.substr(i, 1) == ")")
        
            if(polynomial)
            
                polynomial0 = polyInfo.substr(startPosition, (i - 1));
                polynomial = false;

                //
                // To determine whether the program will be adding, subtracting, or multiplying, we
                // set one of the booleans to true depending on which character was found.
                //
                if(polyInfo.substr(i + 1, 1) == "+")
                
                    adding = true;
                

                else if(polyInfo.substr(i + 1, 1) == "-")
                
                    subtracting = true;
                

                else if(polyInfo.substr(i + 1, 1) == "*")
                
                    multiplying = true;
                
            

            else
            
                polynomial1 = polyInfo.substr(startPosition, i - startPosition);
            
        
    

    polynomial2 = polynomial0;

    //
    // For loops and if statements are used to parse the string into an array so we will be able to 
    // easily handle the coefficients and powers later on for the operations.
    //
    for(int i = 0; i < polynomial2.length(); ++i)
    
        if(i == 0)
        
            if(polynomial2.substr(0, 1) == "x")
            
                polyArray0[counter][0] = 1;

                if(polynomial2.substr(1, 1) != "^")
                
                    polyArray0[counter][1] = 1;
                    ++counter;
                
            

            else
            
                number = polynomial2.substr(0, 1);
                polyArray0[counter][0] = atoi(number.c_str());

                if(polynomial2.substr(i, 1) == "-")
                
                    polyArray0[counter][0] *= -1;
                

                if(polynomial2.substr(1, 1) != "*")
                
                    polyArray0[counter][1] = 0;
                    ++counter;
                

                else if((polynomial2.substr(i + 2, 1) == "*") && (polynomial2.substr(i + 5, 1) != "^"))
                
                    polyArray0[counter][1] = 1;
                    ++counter;
                
            
        

        else if((polynomial2.substr(i, 1) == "-") || (polynomial2.substr(i, 1) == "+"))
        
            if(polynomial2.substr(i + 1, 1) == "x")
            
                polyArray0[counter][0] = 1;

                if(polynomial2.substr(i, 1) == "-")
                
                    polyArray0[counter][0] *= -1;
                

                if(polynomial2.substr(i + 2, 1) != "^")
                
                    polyArray0[counter][1] = 1;
                    ++counter;
                
            

            else
            
                number = polynomial2.substr(i + 1, 1);
                polyArray0[counter][0] = atoi(number.c_str());

                if(polynomial2.substr(i, 1) == "-")
                
                    polyArray0[counter][0] *= -1;
                

                if(polynomial2.substr(i + 2, 1) != "*")
                
                    polyArray0[counter][1] = 0;
                

                else if((polynomial2.substr(i + 2, 1) == "*") && (polynomial2.substr(i + 4, 1) != "^"))
                
                    polyArray0[counter][1] = 1;
                    ++counter;
                
            
        

        else if(polynomial2.substr(i, 1) == "^")
        
            number = polynomial2.substr(i + 1, 1);
            polyArray0[counter][1] = atoi(number.c_str());
            ++counter;
        
    

        polynomial2 = polynomial1;

        for(int i  = 0; i < polynomial2.length(); ++i)
        
            if(i == 0)
            
                if(polynomial2.substr(0, 1) == "x")
                
                    polyArray0[iteration][0] = 1;

                    if(polynomial2.substr(1, 1) != "^")
                    
                        polyArray1[iteration][1] = 1;
                        ++iteration;
                    
                

                else
                
                    number = polynomial2.substr(0, 1);
                    polyArray1[iteration][0] = atoi(number.c_str());

                    if(polynomial2.substr(i, 1) == "-")
                    
                        polyArray0[counter][0] *= -1;
                    

                    if(polynomial2.substr(1, 1) != "*")
                    
                        polyArray1[iteration][1] = 0;
                        ++iteration;
                    

                    else if((polynomial2.substr(i + 1, 1) == "*") && (polynomial2.substr(i + 3, 1) != "^"))
                    
                        polyArray1[iteration][1] = 1;
                        ++iteration;
                    
                
            

            else if((polynomial2.substr(i, 1) == "+") || (polynomial2.substr(i, 1) == "-"))
            
                if(polynomial2.substr(i + 1, 1) == "x")
                
                    polyArray1[iteration][0] = 1;

                    if(polynomial2.substr(i, 1) == "-")
                    
                        polyArray0[counter][0] *= -1;
                    

                    if(polynomial2.substr(i + 2, 1) != "^")
                    
                        polyArray1[iteration][1] = 1;
                        ++iteration;
                    
                

                else
                
                    number = polynomial2.substr(i + 1, 1);
                    polyArray1[iteration][0] = atoi(number.c_str());

                    if(polynomial2.substr(i, 1) == "-")
                    
                        polyArray0[counter][0] *= -1;
                    

                    if(polynomial2.substr(i + 2, 1) != "*")
                    
                        polyArray1[iteration][1] = 0;
                        ++iteration;
                    

                    else if((polynomial2.substr(i + 2, 1) == "*") && (polynomial2.substr(i + 4, 1) != "^"))
                    
                        polyArray1[iteration][1] = 1;
                        ++iteration;
                    
                
            

            else if(polynomial2.substr(i, 1) == "^")
            
                number = polynomial2.substr(i + 1, 1);
                polyArray1[iteration][1] = atoi(number.c_str());
                ++iteration;
            
        

        //
        // If the program found a "+" it will call the addition function and store the answer in "newPolynomial."
        // Similar process with subtracting and multiplying.
        //
        if(adding)
        
            newPolynomial = addition(polyArray0, polyArray1, counter, iteration);
        

        else if(subtracting)
        
            newPolynomial = subtraction(polyArray0, polyArray1, counter, iteration);
        

        else
        
            newPolynomial = multiplication(polyArray0, polyArray1, counter, iteration);
        

        number = newPolynomial.substr(0, 1);
        updated = atoi(number.c_str());

        for(int i = 1; i < (updated + 1); ++i)
        
            number = newPolynomial.substr(i, 1);
            polyArray0[i][0] = atoi(number.c_str());
            number = newPolynomial.substr((i + updated), 1);
            polyArray0[i][1] = atoi(number.c_str());
        

        for(int i = 0; i < updated; ++i)
        
            cout << polyArray0[i][0] << "x^" << polyArray0[i][1];

            if(polyArray0[i][0] > 0 && i != updated)
            
                cout << "+";
            
        

    cout << endl;
    system("PAUSE");
    return 0;

【问题讨论】:

请发布一个 main() 程序,以及使用的数据。此外,这可能会让人感到震惊,但程序员,无论多么先进,都无法仅仅通过注视堆积如山的代码来找出问题所在。它需要在调试器下运行。 这是做什么的? line = static_cast&lt;ostringstream*&gt;(&amp;(ostringstream() &lt;&lt; (updated + counter)))-&gt;str(); 为什么要全部投到ostringstream* ) 和 ( 之间的字符是 + 还是 * ?C++ 有这些漂亮的东西称为类。也许多项式类有助于组织你的代码。注释是解释数据结构的好方法。解释你的poly[MAX][2] 数据结构将帮助人们阅读您的代码。 对于我使用的示例,它是一个“+”。但是,我应该能够将其更改为“*”或“-”并且程序输出正确答案。我没有使用课程,因为我对它们几乎没有经验。 【参考方案1】:

这是一个正确实现加法运算的程序。

本期节目中值得一提的关键点:

    您可以在一维数组中表示多项式的系数。 x^N 的系数位于数组中的第 N 位。无需处理二维数组的复杂性。

    将多项式相加操作与将多项式转换为可显示字符串的方法分开。

我会留给你扩展代码来实现减法和乘法运算。

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

#define MAX_SIZE 10

string polyArrayToString(double polyArray[])

   ostringstream ostr;
   bool empty = true;
   for(int n = MAX_SIZE-1; n >= 0; --n)
   
      if ( polyArray[n] != 0 )
      
         if ( !empty )
         
            ostr << " + ";
         

         ostr << polyArray[n];
         if ( n > 0 )
         
            ostr << "*x^" << n;
         
         empty = false;
      
   

   return ostr.str();


void addition(double polyArray0[],
              double polyArray1[],
              double polyArrayRes[])

   for(int n = 0; n < MAX_SIZE; ++n)
   
      polyArrayRes[n] = polyArray0[n] + polyArray1[n];
   


int main()

   // (2*x^2+3*x^4+5*x+6)
   double polyArray0[MAX_SIZE] = 0;
   polyArray0[0] = 6;
   polyArray0[1] = 5;
   polyArray0[2] = 2;
   polyArray0[4] = 3;

   // (1*x^5+4*x^2+7*x)
   double polyArray1[MAX_SIZE] = 0;
   polyArray1[1] = 7;
   polyArray1[2] = 4;
   polyArray1[5] = 1;

   double polyArrayRes[MAX_SIZE] = 0;
   addition(polyArray0, polyArray1, polyArrayRes);

   cout << "polyArray0: " << polyArrayToString(polyArray0) << endl;
   cout << "polyArray1: " << polyArrayToString(polyArray1) << endl;
   cout << "polyArray0 + polyArray1: " << polyArrayToString(polyArrayRes) << endl;

   return 0;

【讨论】:

我使用了我所做的方法,因为我假设我看不到多项式,这意味着我不知道哪些幂将是相同的。我使用 2D 数组来存储系数和幂,以便稍后比较幂,知道我可以将哪些系数相加或相减。

以上是关于带有多项式的 C++ 方程的主要内容,如果未能解决你的问题,请参考以下文章

如何从多项式拟合中提取方程?

稳定高效地求解大噪声多项式方程

怎样用SPSS做二次多项式回归方程

机器学习多项式回归

在 PL/SQL 中求解多项式方程

如何从多项式中制作多合一多项式?