简体   繁体   English

C ++初学者多项式程序

[英]Beginner polynomial program in C++

I'm looking for some assistance on an exercise for my C++ programming class. 我正在为我的C ++编程课程的练习寻求帮助。 Unfortunately, I was rather ill this week and unable to attend class, meaning I have only been able to use the textbook as a resource, so I'm pretty lost when it comes to writing this program. 不幸的是,本周我病得很重,无法上课,这意味着我只能将教科书用作资源,因此编写此程序时我很迷失。 Therefore, I figured I'd turn to the real pros here for assistance. 因此,我认为我会向真正的专业人士寻求帮助。 I realize this is broad, but any help and/or tips would be appreciated. 我意识到这是广泛的,但是任何帮助和/或技巧都将不胜感激。 Here are the instructions we were given: 这是我们得到的指示:

This assignment deals with representing and manipulating polynomials using simple arrays. 此分配处理使用简单数组表示和处理多项式。 A polynomial, such as anxn + an-1xn-1 + … + a0, will be implemented as an array of coefficients, with >coefficient ai being stored in location i of the array. 多项式,例如anxn + an-1xn-1 +…+ a0,将被实现为一个系数数组,其中系数ai存储在数组的位置i中。 The coefficients are floating point values (potentially negative), so we will use an array of type double. 系数是浮点值(可能为负),因此我们将使用double类型的数组。 The array will be of size MAXPOLY (a constant variable set to 50) and so we will be limited to holding polynomials with maximum degree of MAXPOLY – 1 (or 49). 该数组的大小为MAXPOLY (将常量设置为50),因此我们将限于保存最大程度为MAXPOLY – 1(或49)的多项式。

The file Poly.h describes all the functions provided by the class. 文件Poly.h描述了该类提供的所有功能。

You are to implement the following set of functions: 您将实现以下功能集:
- Default constructor to initialize a polynomial to the zero polynomial -默认构造函数将多项式初始化为零多项式
- setCoeff to set a specific coefficient in the polynomial -setCoeff以在多项式中设置特定系数
- retrieveCoeff to get a specific coefficient from the polynomial -restoreCoeff以从多项式获得特定系数
- incrementCoeff to add a value to a specific coefficient in the polynomial - 增加系数以将值添加到多项式中的特定系数
- degree which determines the degree of the polynomial - 程度它决定了多项式的次数
- numOfTerms which determines the number of terms in the polynomial (ie, how many array elements are nonzero) -numOfTerms ,它确定多项式中的项数(即,有多少个数组元素为非零)
- evaluate which evaluates the polynomial for a given value of X - 评估针对给定的X值评估多项式
- add which adds one polynomial to another, changing the polynomial added to - 加法将一个多项式与另一个多项式相加,更改添加到的多项式
- derivative which computes the derivative of a polynomial - 衍生物 ,其计算多项式的导数
- equals which determines the equality of two polynomials - 等于 ,确定两个多项式的相等性

Several functions are provided for you: (1) a toString function will be provided to you so that >all our polynomials will be displayed identically, (2) the insertion operator is defined so we can >easily print a polynomial, and (3) the equality, inequality, and addition operators are provided >and are simply defined in terms of your equals and add functions. 为您提供了几个函数:(1)将为您提供toString函数,以便所有我们的多项式都将以相同的方式显示;(2)定义了插入运算符,以便我们可以轻松地打印多项式;以及(3)提供了等于,不等式和加法运算符,并且这些运算符仅根据equals和add函数来定义。 You should not change any of the provided functions. 您不应更改任何提供的功能。

You will be supplied two starter files, Poly.cpp and Poly.h . 您将获得两个入门文件Poly.cppPoly.h。 The class declaration file Poly.h contains a complete specification of a class named Poly. 类声明文件Poly.h包含名为Poly的类的完整规范。 Your task will be to implement >all the specified functions in the class definition file Poly.cpp (with the exception of the few >functions which have been provided for you.). 您的任务是在类定义文件Poly.cpp中实现所有指定的功能(为您提供的一些功能除外)。 You have also been provided with an initial test >program PolyTest.cpp. 还为您提供了一个初始测试>程序PolyTest.cpp。 You should add code to the PolyTest.cpp file to fully test your Poly class(copy code from the PolyTest.cpp file you created for Project #1-Pre). 您应该将代码添加到PolyTest.cpp文件中以完全测试Poly类(从为Project#1-Pre创建的PolyTest.cpp文件中复制代码)。

We were, indeed, supplied those files. 实际上,我们已经提供了这些文件。 The Poly.h file looks like this: Poly.h文件如下所示:

#define POLY_H
#ifndef POLY_H
#include <string>
using namespace std;

const size_t MAXPOLY = 50;    

class Poly
{

private:
    // Data members   [implementation of ADT's data object]

    // array for holding the coefficients of the poly
    double coeff[MAXPOLY];               
public:

    // Default Class constructor: initializes a polynomial to the constant 0
    // note: all array elements of coeff[] must be set to 0.0  
    Poly ();

    // degree: finds the degree of a polynomial (the highest power with a non-zero coefficient)
    size_t degree () const;

    // setCoeff: sets a term, value*x^i, in a polynomial
        // Throws <std::out_of_range> if index i does not meet the precondition.
    void setCoeff (double value, size_t i);

    // retrieveCoeff: finds the coefficient of the x^i term in poly
    // Throws <std::out_of_range> if index i does not meet the precondition.
    double retrieveCoeff (size_t i) const;

    // incrementCoeff: changes a term, value*x^i, in a polynomial
    // Throws <std::out_of_range> if index i does not meet the precondition.
    void incrementCoeff(double value, size_t i);

    // toString: produce a string representation of a Poly object
    // note: This function has been provided for you -- DO NOT CHANGE IT!
    string toString() const;

    // numOfTerms: returns the number of terms in the polynomial.
    size_t numOfTerms () const;

    // evaluate: evaluate a polynomial for a specified value of X
    double evaluate (double x) const;

    // add: add one polynomial to another
    void add (const Poly& aPoly);

    // addition operator: add two polynomials together and return a new polynomial that is the result
    // note: This function has been provided for you -- DO NOT CHANGE IT!
    Poly operator+ (const Poly& rhs) const;

    // equals: determine if two polynomials are equal
    bool equals (const Poly& aPoly) const;

    // Equality/inequality operators
    // note: These functions have been provided for you -- DO NOT CHANGE IT!
    bool operator== (const Poly& rhs) const;
    bool operator!= (const Poly& rhs) const;

    // derivative: compute the derivative of a polynomial
    void derivative ();

    // insertion operator for output
    // note: This function has been provided for you -- DO NOT CHANGE IT!
    friend ostream& operator<< (ostream& os, const Poly &p);
};  

#endif

The Poly.cpp file looks like this: Poly.cpp文件如下所示:

#include <iostream>
#include <sstream>
#include <stdexcept>
#include <cmath>
#include "Poly.h"
using namespace std;


// Class constructor
Poly::Poly ()
{
    //ADD YOUR CODE HERE
}

// degree
size_t Poly::degree() const
{
    //ADD YOUR CODE HERE
}

// setCoeff
void Poly::setCoeff (double value, size_t i)
{
    // ADD YOUR CODE HERE
}

// retrieveCoeff
double Poly::retrieveCoeff (size_t i) const
{
    return 0;    // REPLACE WITH YOUR CODE
}

// incrementCoeff
void Poly::incrementCoeff(double value, size_t i)
{
    // ADD YOUR CODE HERE
}

// toString
string Poly::toString() const
{
    ostringstream result;
    bool printedSomething = false;
    for (int i=(int)degree(); i>=0; i--) 
    {
          double c = retrieveCoeff(i);
          if (c != 0.0) 
      {
          printedSomething = true;
          if (i == 0) 
      {
              result.setf(ios::showpos);
              result << " " << c;
              result.unsetf(ios::showpos);
          }
          else 
      {
              result.setf(ios::showpos);
              result << " " << c;
              result.unsetf(ios::showpos);
              result << "*X^" << i;
          }
          }
      }
    if (!printedSomething) 
    {
        result.setf(ios::showpos);
        result << " " << 0;
        result.unsetf(ios::showpos);
    }
    return result.str();
}


// numOfTerms
size_t Poly::numOfTerms () const
{
    return 0;   // REPLACE WITH YOUR CODE
}

// evaluate
double Poly::evaluate (double x) const
{
    return 0;   // REPLACE WITH YOUR CODE
}

// add
void Poly::add (const Poly& aPoly)
{
    // ADD YOUR CODE HERE
}

// addition operator
Poly Poly::operator+ (const Poly& rhs) const
{
    Poly result;
    result.add(*this);
    result.add(rhs);
    return result;
}

// equals
bool Poly::equals (const Poly& aPoly) const
{
    return false;   // REPLACE WITH YOUR CODE
}

// Equality/inequality operators
bool Poly::operator== (const Poly& rhs) const
{
    return equals(rhs);
}

bool Poly::operator!= (const Poly& rhs) const
{
    return !equals(rhs);
}

// derivative
void Poly::derivative ()
{
    // ADD YOUR CODE HERE
}

// Friend operator for printing a Poly object.
ostream & operator << (ostream &out, const Poly& p)
{
    out << p.toString();
    return out;
}

#endif

Although I have a basic understanding of C++, this is only the second week of classes (apparently a bad one to miss), so I am still in the learning stages. 尽管我对C ++有基本的了解,但这只是课程的第二周(显然是一个很差的课程),因此我仍处于学习阶段。 Any help, even if it is just a place to start, would be greatly appreciated. 任何帮助,即使只是开始的地方,也将不胜感激。 Thank you! 谢谢!

Note: I am compiling in Microsoft Visual Studio if that is of any help 注意:如果有任何帮助,我正在Microsoft Visual Studio中进行编译

Couple of things with your posted code. 几件事与您发布的代码。

  1. You need to switch the following lines in Poly.h : 您需要在Poly.h切换以下行:

     #define POLY_H #ifndef POLY_H 

    Otherwise, nothing from the file gets included. 否则,文件中将不包含任何内容。

  2. It's a bad practice to use 不好用

     using namespace std; 

    in a .h file. 在.h文件中。 Use explicit type names, such as std::string and std::ostream . 使用显式类型名称,例如std::stringstd::ostream

Coming to your main obstacle, you have to figure out how to implement the functions in Poly.cpp . 遇到主要障碍时,您必须弄清楚如何实现Poly.cpp的功能。 You can use a test driven approach to flesh out the contents of the file. 您可以使用测试驱动的方法来充实文件的内容。

Let's say you have a file named TestPoly.cpp . 假设您有一个名为TestPoly.cpp的文件。 The file contains the main function and drives testing of the implementation of Poly . 该文件包含main功能,并驱动Poly的实现测试。

You can start with: 您可以从以下内容开始:

void testSetCoeff();

int main()
{
   testSetCoeff();
   return 0;
}

How would you implement testSetCoeff ? 您将如何实现testSetCoeff

Here's something to start off: 这是要开始的事情:

void testSetCoeff()
{
   std::cout << "Testing setCoeff()/retrieveCoeff(): ";

   // Construct an instance of Poly.
   Poly p;

   // Set the 0-the coefficient.       
   p.setCoeff(1.0, 0);

   // Retrieve the same coefficient.
   double c = p.retrieveCoeff(0);

   // Make sure that we get the same value.
   if ( almostEqual(c, 1.0) )
   {
      std::cout << "SUCCESS\n";
   }
   else
   {
      std::cout << "FAILURE\n";
   }
}

The strategy followed in the function: 功能中遵循的策略:

  1. Set some data on an object. 在对象上设置一些数据。
  2. Retrieve the data from the same object. 从同一对象检索数据。
  3. Make sure that you get back a value that makes sense. 确保您获得了一个有意义的值。 Add an appropriate test for it. 为此添加一个适当的测试。

In the function above, I chose to use 在上面的功能中,我选择使用

   if ( almostEqual(c, 1.0) )

instead of 代替

   if ( c == 1.0 )

to make sure that we are able to deal with the inexact nature of floating point representations. 以确保我们能够处理浮点表示形式的不精确性。

The implementation of almostEqual is something like: almostEqual的实现类似于:

bool almostEqual(double x, double y)
{
   static double const tolerance = 1.0E-6;
   return (fabs(x-y) < tolerance);
}

Putting these all together, the content of the starter version of TestPoly.cc will be: 将所有这些放在一起, TestPoly.cc入门版的TestPoly.cc将是:

#include "Poly.h"

#include <iostream>
#include <cmath>

bool almostEqual(double x, double y);
void testSetCoeff();

int main()
{
   testSetCoeff();
   return 0;
}

bool almostEqual(double x, double y)
{
   static double const tolerance = 1.0E-6;
   return (fabs(x-y) < tolerance);
}

void testSetCoeff()
{
   std::cout << "Testing setCoeff()/retrieveCoeff(): ";

   // Construct an instance of Poly.
   Poly p;

   // Set the 0-the coefficient.       
   p.setCoeff(1.0, 0);

   // Retrieve the same coefficient.
   double c = p.retrieveCoeff(0);

   // Make sure that we get the same value.
   if ( almostEqual(c, 1.0) )
   {
      std::cout << "SUCCESS\n";
   }
   else
   {
      std::cout << "FAILURE\n";
   }
}

With the current state of Poly.cpp , you will get FAILURE status. 使用Poly.cpp的当前状态,您将获得FAILURE状态。 Now you can go to Poly.cpp and figure out how to change the implementations of setCoeff and retrieveCoeff to make that test pass. 现在,您可以转到Poly.cpp并找出如何更改setCoeffretrieveCoeff的实现以使测试通过。

// setCoeff
void Poly::setCoeff (double value, size_t i)
{
   coeff[i] = value;
}

// retrieveCoeff
double Poly::retrieveCoeff (size_t i) const
{
   return coeff[i];
}

Then, you can start adding other tests. 然后,您可以开始添加其他测试。 They will most likely fail first. 他们很可能会首先失败。 Then you implement the necessary functions until those tests pass. 然后,您将实现必要的功能,直到这些测试通过。

Update, in response to OP's comment 更新,以回应OP的评论

The coefficients can be initialized to 0 in the constructor using memset . 可以使用memset在构造函数中将系数初始化为0

Poly::Poly ()
{
   memset(coeff, 0, sizeof(coeff));
}

PS: Remember to #include cstring to use memset . PS:记住要#include cstring来使用memset

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM