Cannot retrieve data values from array quadraticExpression - c++

So, in class for work we have to write a header class for quadratic expression. I have the header file done for the most part, however, when I proceed to run with the given .cpp file to test out the header file, it does not appear to read the values given in the array in the cpp file. When I debug, it just puts in garbage values for the values. To me I thought it made sense and can't see anything wrong with it. Unless am I missing something?
I constructed the following header file...
#pragma once
#include <cmath>
enum roots {
NO_ROOTS = 0,
ONE_ROOT = 1,
TWO_ROOTS = 2,
INFINITE_ROOTS = 3
};
class quadraticExpression
{
private:
double a, b, c;
public:
double evaluate(double x) const;
int getNumberOfRoots() const;
double getFirstRoot() const;
double getSecondRoot() const;
double getACoefficient() const;
double getBCoefficient() const;
double getCCoefficient() const;
quadraticExpression();
quadraticExpression(double a,
double b,
double c);
};
quadraticExpression::quadraticExpression()
{
a = 0;
b = 0;
c = 0;
}
inline quadraticExpression::quadraticExpression(double a, double b, double
c)
{
a = a;
b = b;
c = c;
}
;
double quadraticExpression::evaluate(double x) const
{
double y;
y = (a*(x * x)) + (b * x) + c;
return y;
}
int quadraticExpression::getNumberOfRoots() const
{
//return value from enum
double eins;
double zwei;
eins = getFirstRoot();
zwei = getSecondRoot();
if (eins == 0 && zwei == 0)
{
return TWO_ROOTS;
}
else if (eins == 0 || zwei == 0)
{
return ONE_ROOT;
}
else if (eins != 0 && zwei != 0)
{
return NO_ROOTS;
}
}
double quadraticExpression::getFirstRoot() const
{
//return one x value where y is 0
double root1 = (b * b);
double root2 = (4 * a*c);
double solutionOne;
double zUno;
zUno = (abs(b) + sqrt(root1 - root2)) / (2 * a);
solutionOne = (a*(zUno * zUno)) + (b * zUno) + c;
return solutionOne;
}
double quadraticExpression::getSecondRoot() const
{
//return another x value where y is 0
double root1 = (b * b);
double root2 = (4 * a*c);
double solutionTwo;
double zDos;
zDos = (abs(b) - sqrt(root1 - root2)) / (2 * a);
solutionTwo = (a*(zDos *zDos)) + (b *zDos) + c;
return solutionTwo;
}
double quadraticExpression::getACoefficient() const
{
return a;
}
double quadraticExpression::getBCoefficient() const
{
return b;
}
double quadraticExpression::getCCoefficient() const
{
return c;
}
And here is the .cpp tester file
#include <iostream>
#include "QuadraticExpression.h"
using namespace std;
void evaluateExpression(const quadraticExpression &);
int main()
{
quadraticExpression q[6] = { quadraticExpression(2.1, 3, -7),
quadraticExpression(1.4, 3.9, +7),
quadraticExpression(-.75, 0, 0),
quadraticExpression(0, .3, -7),
quadraticExpression(0, 0, 4),
quadraticExpression() };
for (int i = 0; i<6; i++)
evaluateExpression(q[i]);
return EXIT_SUCCESS;
}
void evaluateExpression(const quadraticExpression &q)
{
int errorsHandled = 0;
cout << q.getACoefficient() << " A " << endl;
cout << q.getBCoefficient() << " B " << endl;
cout << q.getCCoefficient() << " C " << endl;
cout << "f(-5) = " << q.evaluate(-5) << endl;
cout << "f(0) = " << q.evaluate(0) << endl;
cout << "f(5) = " << q.evaluate(5) << endl;
if (q.getNumberOfRoots() == INFINITE_ROOTS)
cout << "The Expression has Infinite Roots" << endl;
else if (q.getNumberOfRoots() == ONE_ROOT)
cout << "The Expression has One Root at x = " << q.getFirstRoot() <<
endl;
else if (q.getNumberOfRoots() == TWO_ROOTS)
{
cout << "The Expression has First Root at x = " << q.getFirstRoot() <<
endl;
cout << "The Expression has Second Root at x = " << q.getSecondRoot() <<
endl;
}
else
cout << "The Expression has No Roots" << endl;
try {
q.getFirstRoot();
}
catch (domain_error e) {
errorsHandled++;
}
try {
q.getSecondRoot();
}
catch (domain_error e) {
errorsHandled++;
}
cout << "Errors Handled: " << errorsHandled << endl;
cout << endl;
cout << endl;
}
I fathom I might not be properly acquiring the data values a, b, and c from the array given in the cpp file therefore it just collects garbage values, however I'm stumped here.

This won't work as you intend.
inline quadraticExpression::quadraticExpression(double a, double b, double c)
{
a = a;
b = b;
c = c;
}
You're just assigning the parameter variables to themselves, not assigning to the member variables of the class. Variables declared in a function take precedence over member variables with the same name.
You should give the parameters different names from the member variables, or assign like this->a = a;.
But if you're just initializing member variables from parameters, you don't need to do assignments at all, initializer lists are preferred (see C++: Where to initialize variables in constructor):
quadraticExpression::quadraticExpression(double a, double b, double c) : a(a), b(b), c(c)
{}
Similarly, the constructor with no arguments should use an initializer list:
quadraticExpression::quadraticExpression() : a(0), b(0), c(0)
{}

Related

I have a problem with my c++ code. Error is C2280

I have an error in my code, I want to display the sume of 2 objects with pointers in a class. Please help me to fix it, maybe is due to the pointers. Can you see what's wrong?
This is the error:
<source>(79): error C2280: 'Pair &Pair::operator =(const Pair &)': attempting to reference a deleted function
<source>(60): note: compiler has generated 'Pair::operator =' here
<source>(60): note: 'Pair &Pair::operator =(const Pair &)': function was implicitly deleted because 'Pair' has a user-defined move constructor
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
class Pair {
int *x, *y;
public:
Pair() {
x = new int(sizeof(x));
y = new int(sizeof(y));
*x = 0;
*y = 0;
}
Pair(int a, int b) {
x = new int(sizeof(x));
y = new int(sizeof(y));
*x = a;
*y = b;
}
Pair(Pair& ob) {
x = new int(sizeof(ob.x));
y = new int(sizeof(ob.y));
*x = *(ob.x);
*y = *(ob.y);
}
Pair(Pair&& ob) {
x = new int(sizeof(ob.x));
y = new int(sizeof(ob.y));
*x = *(ob.x);
*y = *(ob.y);
}
Pair(int a):Pair(a, 0) {
}
void setX(int X) {
*x = X;
}
void setY(int Y) {
*y = Y;
}
int* getX() {
return x;
}
int* getY() {
return y;
}
~Pair() {
delete[]x;
delete[]y;
}
Pair sume(Pair ob1){
Pair ob2;
*(ob2.x) = *(ob1.x) + (*x);
*(ob2.y) = *(ob1.y) + (*y);
return ob2;
}
double media() {
return (double(*x) + double(*y)) / 2;
}
};
int main() {
Pair ob1, ob2(5), ob3(4, 3);
ob1.setX(6);
ob1.setY(7);
cout << "X= " << *(ob1.getX())<<endl;
cout << "Y= " << *(ob1.getY())<<endl;
cout << "Media este: " << ob1.media();
cout << "\nX= " << *(ob2.getX()) << endl;
cout << "Y= " << *ob2.getY() << endl;
cout << "Media este: " << ob2.media();
cout << "\nX= " << *(ob3.getX()) << endl;
cout << "Y= " << *(ob3.getY()) << endl;
cout << "Media este: " << ob3.media();
Pair ob4,ob5,ob6;
ob4 = ob1.sume(ob2);//here the compiler shows the error
cout <<"\nX= "<< *(ob4.getX())<<endl;
cout << "Y= " << *(ob4.getY())<<endl;
}

apply_visitor does not change object

I have inherited from boost::static_visitor<> and defined a class as follows:
class move_visitor : public boost::static_visitor<> {
private:
double m_dx, m_dy;
public:
move_visitor() : m_dx(0.0), m_dy(0.0) {}
move_visitor(double dx, double dy) : m_dx(dx), m_dy(dy) {}
~move_visitor() {}
void operator () (Point &p) const {
p.X(p.X() + m_dx);
p.Y(p.Y() + m_dy);
}
void operator () (Circle &c) const {
Point center_point(c.CentrePoint().X() + m_dx, c.CentrePoint().Y() + m_dy);
c.CentrePoint(center_point);
}
void operator() (Line &l) const {
Point start(l.Start().X() + m_dx, l.Start().Y() + m_dy),
end(l.End().X() + m_dx, l.End().Y() + m_dy);
l.Start(start);
l.End(end);
}
};
This class is supposed to change the x and y position of some objects, Point, Line and Circle.
When I execute the following code:
int main()
{
typedef boost::variant<Point, Line, Circle> ShapeType;
Point p(1, 2);
Line l(p, p);
Circle c(p, 5);
ShapeType shape_variant;
std::cout << p << "\n\n"
<< l << "\n\n"
<< c << "\n\n";
shape_variant = p;
boost::apply_visitor(move_visitor(2, 2), shape_variant);
std::cout << p << std::endl;
shape_variant = l;
boost::apply_visitor(move_visitor(2, 2), shape_variant);
std::cout << std::endl << l << std::endl;
return 0;
}
p remains as 1, 2 and so does l. Why aren't my object changing after 'apply_visitor`?
You're modifying shape_variant, not p or l.
Try
std::cout << boost::get<Point>(shape_variant) << std::endl;
and
std::cout << boost::get<Line>(shape_variant) << std::endl;

Can I specify or select a member of a class (and use it as parameter )?

For example, let's say I have:
class AB { float a,b; };
How do I write one function that can process either a or b, based on a parameter that's passed in, in a "proper" way? I want to do something like this:
float getSqrt(AB x, ClassMemberSelector s)
{ return sqrt(x.s); }
AB x;
getSqrt(x, SelectClassMember(AB::a) ); //get square root of x.a
getSqrt(x, SelectClassMember(AB::b) ); //get square root of x.b
Sure, here are three examples:
1)
float getSqrt(const AB& ab, function<float(const AB&)> selector)
{
return sqrt(selector(ab));
}
which simplifies to (thanks to NathanOliver's comment):
template<typename SelectorT>
float getSqrt(AB ab, SelectorT selector)
{
return sqrt(selector(ab));
}
(this version is better, as it avoids copying a lambda into std::function)
and usage (same for both versions):
cout << getSqrt(x, [](const AB& ab) { return ab.a; }) << endl;
cout << getSqrt(x, [](const AB& ab) { return ab.b; }) << endl;
2)
Another possibility would be to use a pointer to member:
float getSqrt(const AB& ab, float AB::*selector)
{
return sqrt(ab.*selector);
}
and usage:
cout << getSqrt(x, &AB::a) << endl;
cout << getSqrt(x, &AB::b) << endl;
3)
And an example using TMP trait-like overload selection:
struct SelectAMemberT {};
struct SelectBMemberT {};
template<typename SelectorT>
float getSqrt(const AB& ab, SelectorT);
template<>
float getSqrt(const AB& ab, SelectAMemberT)
{
return sqrt(ab.a);
}
template<>
float getSqrt(const AB& ab, SelectBMemberT)
{
return sqrt(ab.b);
}
const SelectAMemberT SelectAMember;
const SelectBMemberT SelectBMember;
and usage:
cout << getSqrt(x, SelectAMember) << endl;
cout << getSqrt(x, SelectBMember) << endl;
#include <iostream>
#include <cmath>
class AB
{
public:
float a, b;
};
float getSqrt(AB x, float AB::*mem)
{
return sqrt(x.*mem);
}
int main()
{
AB x;
x.a = 9;
x.b = 16;
std::cout << "sqrt x.a: " << getSqrt(x, &AB::a) << std::endl;
std::cout << "sqrt x.b: " << getSqrt(x, &AB::b) << std::endl;
system("pause");
return 0;
}

Newton method for computing an inverse

This is following the question I asked in this thread : Link error missing vtable
I defined a class 'function' and two others classes 'polynomial' and 'affine' that inherit from 'function'.
class function {
public:
function(){};
virtual function* clone()const=0;
virtual float operator()(float x)const=0; //gives the image of a number by the function
virtual function* derivative()const=0;
virtual float inverse(float y)const=0;
virtual ~function(){}
};
class polynomial : public function {
protected:
int degree;
private:
float *coefficient;
public:
polynomial(int d);
virtual~polynomial();
virtual function* clone()const;
int get_degree()const;
float operator[](int i)const; //reads coefficient number i
float& operator[](int i); //updates coefficient number i
virtual float operator()(float x)const;
virtual function* derivative()const;
virtual float inverse(float y)const;
};
class affine : public polynomial {
int a;
int b;
//ax+b
public:
affine(int d,float a_, float b_);
function* clone()const;
float operator()(float x)const;
function* derivative()const;
float inverse(float y)const;
~affine(){}
};
Method inverse in polyomial does not seem to work fine. It is based on the Newton method applied to the function x->f(x)-y for fixed y (the element for which we're computing the inverse) and the current polynomial f.
float polynomial::inverse(float y)const
{
int i=0;
float x0=1;
function* deriv=derivative();
float x1=x0+(y-operator()(x0))/(deriv->operator()(x0));
while(i<=100 && abs(x1-x0)>1e-5)
{
x0=x1;
x1=x0+(y-operator()(x0))/(deriv->operator()(x0));
i++;
}
if(abs(x1-x0)<=1e-5)
{
//delete deriv; //I get memory problems when I uncomment this line
return x1;
}
else
{
cout<<"Maximum iteration reached in polynomial method 'inverse'"<<endl;
//delete deriv; //same here
return -1;
}
}
double polynomial::operator()(double x)const
{
double value=0;
for(int i=0;i<=degree;i++) value+=coefficient[i]*pow(x,i);
return value;
}
polynomial* polynomial::derivative()const
{
if(degree==0)
{
return new affine(0,0,0);
}
polynomial* deriv=new polynomial(degree-1);
for(int i=0;i<degree;i++)
deriv[i]=(i+1)*coefficient[i+1];
return deriv;
}
I test this method with p:x->x^3 :
#include "function.h"
int main(int argc, const char * argv[])
{
polynomial p(3);
for(int i=0;i<=2;i++) p[i]=0;
p[3]=1;
cout<<"27^(1/3)="<<p.inverse(27);
return 0;
}
This script outputs 27^(1/3)=Maximum iteration reached in polynomial method 'inverse'
-1 even if I put 10,000 instead of 100. I've read some articles on the internet and it seems that it's a common way to compute the inverse.
the abs function prototype is: int abs(int)
So a test like abs(x1-x0)<=1e-5 won't behave as you expect; you compare a int with a float. In this case the float will be converted to int so it the same as abs(x1-x0)<=0
This is probably why you don't get the expected result - I suggest adding a few more printouts to get to the bottom of things.
Well, the problem was in method 'derivative'. Instead of using the 'operator[]' that I redefined, I used '->coefficient[]' and the main script worked fine for p.inverse(27) (only 14 iterations). I just replaced deriv[i]=(i+1)*coefficient[i+1]; with deriv->coefficient[i]=(i+1)*coefficient[i+1];
Check This Code :
#include<iostream>
#include<cmath>
#include<math.h>
using namespace std;
void c_equation(int choose, double x);
void Processes(double x, double fx1, double fdx1, int choose);
void main()
{
int choose,choose2;
double x;
system("color A");
cout << " " << endl;
cout << "=============================================================" << endl;
cout << "Choose Equation : " << endl;
cout << "_____________________________________" << endl;
cout << "1- x-2sin(x)" << endl;
cout << "2- x^2 + 10 cos(x)" << endl;
cout << "3- e^x - 3x^2" << endl;
cout << " " << endl;
cin >> choose;
cout << "If you have values press 1/ random press 2 :" << endl;
cin >> choose2;
if (choose2 == 1)
{
cout << " " << endl;
cout << "Enter Xo : " << endl;
cin >> x;
c_equation(choose, x);
}
else if (choose2 == 2)
{
x = rand() % 20;
cout << "Xo = " << x << endl;
c_equation(choose, x);
choose2 = NULL;
}
else
{
cout << "Worng Choice !! " << endl;
choose = NULL;
choose2 = NULL;
main();
}
}
void c_equation(int choose, double x)
{
double fx;
double fdx;
double fddx;
double result;
if (choose == 1)
{
fx = x - 2 * sin(x);
fdx = 1 - 2 * cos(x);
fddx = 2 * sin(x);
result = abs((fx * fddx) / pow(fdx, 2));
}
else if (choose == 2)
{
fx = pow(x, 2) + 10 * cos(x);
fdx = 2 * x - 10 * sin(x);
fddx = 2 - 10 * cos(x);
result = abs((fx * fddx) / pow(fdx, 2));
}
else if (choose == 3)
{
fx = exp(x) - 3 * pow(x, 2);
fdx = exp(x) - 6 * x;
fddx = exp(x) - 6;
result = abs((fx * fddx) / pow(fdx, 2));
}
else
{
cout << " " << endl;
}
//------------------------------------------------------------
if (result < 1)
{
cout << "True Equation :) " << endl;
Processes(x, fx, fdx , choose);
}
else
{
system("cls");
cout << "False Equation !!" << endl;
choose = NULL;
x = NULL;
main();
}
}
void Processes(double x, double fx, double fdx , int choose)
{
double xic;
for (int i = 0; i < 3; i++)
{
xic = x - (fx / fdx);
cout << " " << endl;
cout << "Xi = " << x << " " << "F(Xi) = " << fx << " " << " F'(Xi) = " << fdx << " " << " Xi+1 = " << xic << endl;
x = xic;
if (choose == 1)
{
fx = xic - 2 * sin(xic);
fdx = 1 - 2 * cos(xic);
}
else if (choose == 2)
{
fx = pow(xic, 2) + 10 * cos(xic);
fdx = 2 * xic - 10 * sin(xic);
}
else if (choose == 3)
{
fx = exp(xic) - 3 * pow(xic, 2);
fdx = exp(xic) - 6 * xic;
}
}
}

C++ another class member and overloading operator

I need to write program as follow:
#include <iostream>
using namespace std;
class Point
{
public:
double X;
double Y;
Point(){}
Point(double x, double y)
{
X = x;
Y = y;
}
};
class Circle
{
public:
Point P;
double R;
Circle(){}
Circle(Point p, double r)
{
P = p;
R = r;
}
Circle operator +(Circle C1, Circle C2)
{
return Circle(C1.Point, C1.R + C2.R);
}
Circle operator -(Circle C1, Circle C2)
{
return Circle(C2.Point, C1.R - C2.R);
}
};
int main()
{
Circle c1, c2, cr1, cr2, ck1, ck2;
// create c1
// create c2
cr1 = c1 + c2;
// display cr1
cr2 = c2 + c1;
// display cr2
ck1 = c1 - c2;
// display ck1
ck2 = c2 - c1;
// display ck2
return 0;
}
Two classes Point and Circle, where Circle have member of Point as it's center, two operators to add and to subtract two Circles.
And I can't compile this, what is wrong?
#################################################################################
EDIT:
After correction it looks like that, and works perfectly:
#include <iostream>
using namespace std;
class Point
{
public:
double X, Y;
Point(){}
Point(double x, double y)
{
X = x;
Y = y;
}
};
class Circle
{
public:
double R;
Point P;
Circle(){}
Circle(Point p, double b)
{
P = p;
R = b;
}
Circle operator+(const Circle& C1)
{
Circle C;
C.P = this->P;
C.R = this->R + C1.R;
return C;
}
Circle operator -(const Circle& C1)
{
Circle C;
C.P = C1.P;
C.R = this->R - C1.R;
return C;
}
};
int main()
{
double X, Y, R;
cout << "Coordinates for C1:" << endl;
cout << "\tX: ";
cin >> X;
cout << "\tY: ";
cin >> Y;
cout << "Radius for C1:";
cin >> R;
Circle *c1 = new Circle(Point(X, Y), R);
cout << "Coordinates for C2:" << endl;
cout << "\tX: ";
cin >> X;
cout << "\tY: ";
cin >> Y;
cout << "Radius for C2:";
cin >> R;
Circle *c2 = new Circle(Point(X, Y), R);
Circle cs1 = c1->operator+(*c2);
Circle cs2 = c1->operator-(*c2);
Circle cr1 = c2->operator+(*c1);
Circle cr2 = c2->operator-(*c1);
cout << "cs1([" << cs1.P.X << ", " << cs1.P.Y << "], " << cs1.R << ")" << endl;
cout << "cs2([" << cs2.P.X << ", " << cs2.P.Y << "], " << cs2.R << ")" << endl;
cout << "cr1([" << cr1.P.X << ", " << cr1.P.Y << "], " << cr1.R << ")" << endl;
cout << "cr2([" << cr2.P.X << ", " << cr2.P.Y << "], " << cr2.R << ")" << endl;
char ch;
cin >> ch;
return 0;
}
When you define operators like operator- inside your class as member functions, then when you use it
C3 = C1 + C2;
The compiler is actually calling your member function like
C3 = C1.operator+(C2);
From this you should be able to figure out that operators as member functions only takes one argument, and that the first object in the operator is the this object.
For stand-alone (non-member) functions they need two arguments.
You might want to check e.g. this reference on operator overloading.
You have incorrect overloaded operators. Look at the following code:
Circle operator +(const Circle& C)
{
return Circle(this->P, this->R + C.R);
}
Circle operator -(const Circle& C)
{
return Circle(this->P, this->R - C.R);
}