hi guyz, i want to write a program that will find the (sine, cosine and tangent) of adding and subtracting two variables using inheritance and polymorphism concepts. anybody plz help?
appreciate the answer:)
hi guyz, i want to write a program that will find the (sine, cosine and tangent) of adding and subtracting two variables using inheritance and polymorphism concepts. anybody plz help?
appreciate the answer:)
Good starting point, . is right that the standard library supplies trig routines; below is a simple object-oriented pattern that uses inheritance and polymorphism to compute sin/cos/tan of a + b or a - b while keeping code extensible.
The idea: separate the binary operation (add/sub) from the trig function (sin/cos/tan). Make small abstract bases and derive concrete classes. Compose a Combined object that calls the binary op then the trig op — swap any implementation at runtime without if/switch.
#include <cmath>
#include <memory>
struct BinaryOp {
virtual double compute(double a, double b) const = 0;
virtual ~BinaryOp() {}
};
struct Add : BinaryOp { double compute(double a,double b) const override { return a + b; } };
struct Sub : BinaryOp { double compute(double a,double b) const override { return a - b; } };
struct TrigOp {
virtual double apply(double x) const = 0;
virtual ~TrigOp() {}
};
struct SinOp : TrigOp { double apply(double x) const override { return std::sin(x); } };
struct CosOp : TrigOp { double apply(double x) const override { return std::cos(x); } };
struct TanOp : TrigOp { double apply(double x) const override { return std::tan(x); } };
struct Combined {
std::unique_ptr<BinaryOp> bin;
std::unique_ptr<TrigOp> trig;
Combined(BinaryOp* b, TrigOp* t) : bin(b), trig(t) {}
double evaluate(double a,double b) const { return trig->apply(bin->compute(a,b)); }
}; Notes and cautions:
std::sin, std::cos, std::tan expect radians. Convert degrees with rad = deg * (std::acos(-1.0)/180.0).tan(x) blows up near odd multiples of pi/2. Check double c = std::cos(x); if (std::fabs(c) < 1e-12) /* handle singularity */.std::fmod(x, 2*std::acos(-1.0)) before calling trig functions.evaluate() nodes) can represent more complex formulas.Jump to Post— Grn Xtrm 84The cmath library has built in functions to calculate the sin, cos, and tan. Look here for more info:
The cmath library has built in functions to calculate the sin, cos, and tan. Look here for more info:
thanx :)
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.