用C初学者多项式++程序 [英] Beginner polynomial program in C++

查看:133
本文介绍了用C初学者多项式++程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在找上一个练习,我的C ++编程类的一些援助。不幸的是,我是这个星期,而生病而无法上课,这意味着我只能够使用教科书作为一种资源,所以我当谈到写这个程序pretty丢失。所以,我想我会变成真正的职业选手在这里寻求帮助。我意识到这是广泛的,但任何帮助和/或提示,将AP preciated。下面是我们给出的说明:


  

这与分配重新presenting和使用简单的数组操作多项式交易。一个
  多项式,如anxn +一个-1XN-1 + ... + A0,将被实施为系数的阵列,具有>系数ai的被存储在位置i上阵列。系数被浮点值
  (可能为负),因此我们将使用double类型的数组。该阵列将是大小的 MAXPOLY
  (常数变量设置为50),所以我们将只限于保持与最大多项式
  1(或49)搜索结果 - 中的 MAXPOLY 的程度
  该文件的 Poly.h 描述了类提供的所有功能。搜索结果
  你要实现以下的功能集:结果
    - 默认构造函数多项式初始化为零
     多项式结果
    - setCoeff 的设置在多项式结果一个特定的系数
    - retrieveCoeff 的摆脱多项式结果一个特定的系数
    - incrementCoeff 的一个值添加到特定系数多项式结果
    - 这就决定了多项式结果的本科学历
    - numOfTerms 的,它确定了多项式的项数(即,许多阵列元件是如何非零)搜索
    - 评估其计算对于x结果的给定值多项式
    - 添加的其中添加一个多项式到另一个,改变多项式加入到结果
    - 衍生的后者计算多项式结果的导数
    - 等于的决定两个多项式的结果。

平等
  
  

为您提供了几个功能:(1)的的toString 的功能将提供给你,让>我们的所有多项式将相同的显示,(2)插入运算符定义,所以我们可以>轻松打印多项式,和(3)平等,不平等,并提供加法运算>,并且只需在平等来定义,并添加功能。你不应该改变任何提供的功能。


  
  

您将提供的两个启动文件, Poly.cpp Poly.h 。类的声明
  文件Poly.h包含一个名为聚类的完整规范。你的任务将是实施>中的所有类定义文件Poly.cpp特定功能(与已提供给您的为数不多>的功能除外)。您还提供了一个最初的测试>程序PolyTest.cpp。您应该添加code将PolyTest.cpp文件充分测试你的聚类(从PolyTest.cpp副本code文件您创建的项目#1 $​​ P $ P)


我们,事实上,提供这些文件。在 Poly.h 文件看起来是这样的:

 的#define POLY_H
的#ifndef POLY_H
#包括LT&;串GT;
使用命名空间std;常量size_t型MAXPOLY = 50;聚类
{私人的:
    //数据成员[实施ADT的数据对象]    //数组用于保持聚的系数
    双COEFF [MAXPOLY]
上市:    //默认类的构造函数:初始化一个多项式为常量0
    //注意:COEFF的所有数组元素[]必须设置为0.0
    聚();    //度:发现一个多项式的程度(具有非零系数的最高功率)
    为size_t度()const的;    // setCoeff:设置一个期限,价值* X ^ I,在多项式
        //抛出<的std :: out_of_range>如果索引i不满足precondition。
    无效setCoeff(双重价值,为size_t我);    // retrieveCoeff:发现在聚X ^ I项系数
    //抛出<的std :: out_of_range>如果索引i不满足precondition。
    双retrieveCoeff(为size_t我)常量;    // incrementCoeff:改变一个词,值* X ^ I,在多项式
    //抛出<的std :: out_of_range>如果索引i不满足precondition。
    无效incrementCoeff(双重价值,为size_t我);    //的toString:产生一个字符串再一个多边形对象的presentation
    //注:此功能已经为您提供了 - 不要改变它!
    字符串的ToString()const的;    // numOfTerms:返回在多项式的项数。
    为size_t numOfTerms()const的;    //评估:评估一个多项式为X的规定值
    双评估(双X)const的;    //添加:一是多项式添加到另一个
    无效添加(常量聚放大器; aPoly);    //加法运算符:添加两个多项式在一起,并返回一个新的多项式是结果
    //注:此功能已经为您提供了 - 不要改变它!
    保利运营商+(const的聚放;右)常量;    //相当于:确定两个多项式相等
    布尔等于(const的聚放; aPoly)常量;    //平等/不平等的运营商
    //注意:这些功能已被提供给你 - 别更改它!
    布尔运算符==(const的聚放;右)常量;
    布尔运算符=(const的聚放;右)!常量;    //衍生物:计算多项式的导数
    空隙衍生物();    //输出插入运算符
    //注:此功能已经为您提供了 - 不要改变它!
    朋友的ostream&安培;运营商的LT;< (ostream的&安培; OS,常量聚安培; P);
};#万一

Poly.cpp 文件看起来是这样的:

 的#include<&iostream的GT;
#包括LT&;&sstream GT;
#包括LT&;&stdexcept GT;
#包括LT&;&CMATH GT;
#包括Poly.h
使用命名空间std;
//类的构造函数
聚::聚()
{
    //此处添加您的code
}//度
为size_t聚::度()const的
{
    //此处添加您的code
}// setCoeff
无效聚:: setCoeff(双重价值,为size_t I)
{
    //此处添加您的code
}// retrieveCoeff
双聚:: retrieveCoeff(为size_t我)常量
{
    返回0; //替换为您code
}// incrementCoeff
无效聚:: incrementCoeff(双重价值,为size_t I)
{
    //此处添加您的code
}//的toString
字符串聚::的toString()const的
{
    ostringstream结果;
    布尔printedSomething = FALSE;
    的for(int i =(int)的程度(); I> = 0;我 - )
    {
          双c = retrieveCoeff(I)
          如果(C!= 0.0)
      {
          printedSomething = TRUE;
          如果(我== 0)
      {
              result.setf(IOS :: showpos);
              结果<< << C;
              result.unsetf(IOS :: showpos);
          }
          其他
      {
              result.setf(IOS :: showpos);
              结果<< << C;
              result.unsetf(IOS :: showpos);
              结果<< * X ^<<一世;
          }
          }
      }
    如果(!printedSomething)
    {
        result.setf(IOS :: showpos);
        结果<< << 0;
        result.unsetf(IOS :: showpos);
    }
    返回result.str();
}
// numOfTerms
为size_t聚:: numOfTerms()const的
{
    返回0; //替换为您code
}// 评估
双聚::评估(双X)常量
{
    返回0; //替换为您code
}//添加
无效聚::添加(常量聚放大器; aPoly)
{
    //此处添加您的code
}//加法运算符
保利::运算+(const的聚放大器; RHS)常量
{
    保利的结果;
    result.add(*此);
    result.add(右);
    返回结果;
}// 等于
布尔聚::等号(常量聚放大器; aPoly)常量
{
    返回false; //替换为您code
}//平等/不平等的运营商
布尔聚::运算符==(const的聚放大器; RHS)常量
{
    回报等于(右);
}布尔聚::运算符=(const的聚放大器; RHS)!常量
{
    返回的equals(右)!;
}//衍生
无效聚::衍生物()
{
    //此处添加您的code
}//打印一个多边形对象好友运营商。
ostream的&安培;运营商的LT;< (ostream的&安培;出来,常量聚安培; P)
{
    出<< p.toString();
    返回的;
}#万一

虽然我有C ++的一个基本的了解,这仅仅是类的第二周(显然是一个坏的错过),所以我仍然在学习阶段。任何帮助,哪怕仅仅是一个开始的地方,将是极大的AP preciated。谢谢!

注意:我在Microsoft Visual Studio编译如果这是任何帮助。


解决方案

的东西与你的贴code夫妇。


  1. 您需要切换以下行 Poly.h

     的#define POLY_H
    的#ifndef POLY_H

    另外,从文件中没有被包括在内。


  2. 这是一个不好的做法,使用

     使用命名空间std;

    在.h文件中。使用显式类型的名称,如的std ::字符串的std :: ostream的


来你的主要障碍,你必须弄清楚如何实施 Poly.cpp 的功能。您可以使用测试驱动的方法来充实该文件的内容。

让我们假设你有一个名为 TestPoly.cpp 。该文件包含保利

的实施功能和驱动器测试

您可以启动:

 无效testSetCoeff();诠释的main()
{
   testSetCoeff();
   返回0;
}

你将如何实施 testSetCoeff

下面的东西开始:

 无效testSetCoeff()
{
   性病::法院LT&;< 测试setCoeff()/ retrieveCoeff();   //构造保利的一个实例。
   聚对;   //设置0系数。
   p.setCoeff(1.0,0);   //获得系数相同。
   双c = p.retrieveCoeff(0);   //确保我们得到相同的值。
   如果(almostEqual(C,1.0))
   {
      性病::法院LT&;< 成功\\ n;
   }
   其他
   {
      性病::法院LT&;< 失败\\ n;
   }
}

该战略遵循的功能:


  1. 设置在对象上的一些数据。

  2. 从同一个对象检索数据。

  3. 确保你得到一个值,这是很有意义的。添加适当的测试吧。

在上面的功能,我选择使用

 如果(almostEqual(C,1.0))

而不是

 如果(C = = 1.0)

,以确保我们能够处理浮点再presentations的不精确性。

almostEqual 的实施是这样的:

 布尔almostEqual(双X,双Y)
{
   静态常量双宽容= 1.0E-6;
   回报(晶圆厂(X-Y)LT;宽容);
}

把这些放在一起的 TestPoly.cc 的首发版本的内容将是:

 的#includePoly.h#包括LT&;&iostream的GT;
#包括LT&;&CMATH GT;布尔almostEqual(双X,双Y);
无效testSetCoeff();诠释的main()
{
   testSetCoeff();
   返回0;
}布尔almostEqual(双X,双Y)
{
   静态常量双宽容= 1.0E-6;
   回报(晶圆厂(X-Y)LT;宽容);
}无效testSetCoeff()
{
   性病::法院LT&;< 测试setCoeff()/ retrieveCoeff();   //构造保利的一个实例。
   聚对;   //设置0系数。
   p.setCoeff(1.0,0);   //获得系数相同。
   双c = p.retrieveCoeff(0);   //确保我们得到相同的值。
   如果(almostEqual(C,1.0))
   {
      性病::法院LT&;< 成功\\ n;
   }
   其他
   {
      性病::法院LT&;< 失败\\ n;
   }
}

使用 Poly.cpp 的当前状态,您将获得失败状态。现在,你可以去 Poly.cpp ,并找出如何改变 setCoeff 的实施和 retrieveCoeff 来使该测试通过。

  // setCoeff
无效聚:: setCoeff(双重价值,为size_t I)
{
   COEFF [I] =价值;
}// retrieveCoeff
双聚:: retrieveCoeff(为size_t我)常量
{
   返回COEFF [I]
}

然后,你就可以开始添加其他测试。他们将最有可能首先会失败。然后你实现必要的功能,直到这些测试都通过了。

更新,以应对OP的评论

//en.cp$p$pference.com/w/cpp/:

该系数可以在构造函数中使用的 0 字符串/字节/ memset的相对=nofollow> memset的

 聚::聚()
{
   memset的(COEFF,0,sizeof的(COEFF));
}

PS:记住需要#include 的CString 使用 memset的

I'm looking for some assistance on an exercise for my C++ programming class. 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. The coefficients are floating point values (potentially negative), so we will use an array of type 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).

The file Poly.h describes all the functions provided by the class.

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
- retrieveCoeff to get a specific coefficient from the polynomial
- 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 (i.e., how many array elements are nonzero)
- evaluate which evaluates the polynomial for a given value of 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. You should not change any of the provided functions.

You will be supplied two starter files, Poly.cpp and Poly.h. The class declaration file Poly.h contains a complete specification of a class named 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.). You have also been provided with an initial test >program 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).

We were, indeed, supplied those files. The Poly.h file looks like this:

#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:

#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. 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

解决方案

Couple of things with your posted code.

  1. You need to switch the following lines in 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. Use explicit type names, such as std::string and std::ostream.

Coming to your main obstacle, you have to figure out how to implement the functions in 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. The file contains the main function and drives testing of the implementation of Poly.

You can start with:

void testSetCoeff();

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

How would you implement 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:

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:

#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. Now you can go to Poly.cpp and figure out how to change the implementations of setCoeff and retrieveCoeff to make that test pass.

// 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

The coefficients can be initialized to 0 in the constructor using memset.

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

P.S.: Remember to #include cstring to use memset.

这篇关于用C初学者多项式++程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆