CMPS 148: Homework 3 C++ Write a class that models a polynomial equation of the
ID: 3567515 • Letter: C
Question
CMPS 148: Homework 3 C++
Write a class that models a polynomial equation of the form:
ax2 + bx + c = 0
The class should have 3 properties, A, B, and C. You are to provide several functions as well,
including an evaluate function that accepts an
Explanation / Answer
Polynomial.h
-----------------------------
class Polynomial
{
private:
double A;
double B;
double C;
public:
Polynomial()
{
A=0;
B=0;
C=0;
}
Polynomial(double a, double b, double c)
{
A=a;
B=b;
C=c;
}
void setA(double a)
{
A=a;
}
void setB(double b)
{
B=b;
}
void setC(double c)
{
C=c;
}
double evaluate(double x)
{
return ((A*x*x) + (B*x) + C );
}
bool findRoots(double &r1, double &r2)
{
double cond = ((B*B) - (4*A*C));
if(cond < 0)
return false;
else
{
cond = sqrt(cond);
r1 = ((-B) + cond)/(2*A);
r2 = ((-B) - cond)/(2*A);
return true;
}
}
void print()
{
cout<<A<<"x^2 + "<<B<<"x + "<<C<<" ";
}
};
--------------------------------------------------------------------------------------------------------------------
main.cpp
-----------------------------
#include <iostream>
#include "Polynomial.h"
using namespace std;
void printRoots(Polynomial p) {
double r1=0, r2=0;
if ( p.findRoots(r1, r2) ) {
cout << " with roots at " << r1 << " and " << r2 << endl;
}
else {
cout << " No Roots" << endl;
}
}
int main() {
Polynomial p1(14, 19, 2); // Provide a constructor to set A, B, C
Polynomial p2; // Default constructor should initialize to all zeros
double tmp;
cout << "Enter A: ";
cin >> tmp;
p2.setA(tmp); // A, B, and C need to be private variables - supply getters and setters.
cout << "Enter B: ";
cin >> tmp;
p2.setB(tmp);
cout << "Enter C: ";
cin >> tmp;
p2.setC(tmp);
cout << "Two polynomials will be used:" << endl;
cout << "P1: Predefined: ";
p1.print(); // Should print as 14x^2 + 19x + 2
cout << "P2: User-Defined: ";
p2.print(); // Should print in the same format, but with the user-entered values.
cout << "Enter an x value to evaluate both polynomials: ";
cin >> tmp;
cout << "P1: " << p1.evaluate(tmp) << endl;
printRoots(p1);
cout << "P2: " << p2.evaluate(tmp) << endl;
printRoots(p2);
}