Jump to content
xisto Community
Томму

Exercises How about some programming exercises :)

Recommended Posts

It's simple, someone posts an exercise, the other one solves it, and so on ;).

Okay, let's start.

Ohm's law Make a class describing a resistor with the following members:

a private data member for the resistance, R

a public member function to set the value of R

a public member function to calculate the current I from the voltage E

a public member function to calculate the voltage E from the current I

a public member function to calculate the power dissipation P from the current I using the formula P = I?E, where E is calculated using the previous member function.

Make a program to test this class.

Share this post


Link to post
Share on other sites
#include <iostream>class Resistor{   float R;public:   Resistor& setR(float r) { R=r; return *this; }   float getI(float E) { return E/R; }   float getE(float I) { return R*I; }   float getP(float I) { return I*getE(I); }   Resistor() :R(0) {}   Resistor(float r) :R(r) {}};int main() {   Resistor r(5);   std::cout << "Resistor(5).getE(0.5) = " << r.getE(0.5f) << " V" << std::endl;   std::cout << "Resistor(100).getI(12) = " << r.setR(100).getI(12) << " A" << std::endl;   std::cout << "Resistor(1200).getP(0.01) = " << r.setR(1200).getP(0.01) << " W" << std::endl;   return 0;}

Ok, so here is a silly one from me.

Let Variables be a map of string to float:
typedef std::map<std::string,float> Variables;

Let Operation be an abstract class that has the following declaration:
struct Operation {   virtual float evaluate(const Variables& vars) = 0;};

Implement Add, Sub, Mul, Div, Const, Var that extend Operation so that the following example is possible:

// Create expression: (A+10)*(1/(B-3))Mul expression(	Add( Var("A"), Const(10) ),	Div( Const(1),		Sub(Var("B"),Const(3))		)	);// Create variable mapVariables vars;vars["A"] = 2.5;vars["B"] = 7;// Evaluate expression using variables in vars mapfloat result = expression.evaluate(vars);
You may add abstract methods to Operation.
Edited by nooc9 (see edit history)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.