Jump to content



Welcome to KnowledgeSutra - Dear Guest , Please Register here to get Your own website. - Ask a Question / Express Opinion / Reply w/o Sign-Up!
- - - - -

Exercises


1 reply to this topic

#1 Томму

    Newbie [Level 1]

  • Kontributors
  • Pip
  • 12 posts

Posted 15 August 2009 - 10:41 PM

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:

Quote

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

#2 nooc9

    Newbie [Level 2]

  • Kontributors
  • PipPip
  • 31 posts

Posted 28 October 2009 - 07:37 AM

#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 map
Variables vars;
vars["A"] = 2.5;
vars["B"] = 7;

// Evaluate expression using variables in vars map
float result = expression.evaluate(vars);
You may add abstract methods to Operation.

Edited by nooc9, 28 October 2009 - 07:45 AM.





Reply to this topic


This post will need approval from a moderator before this post is shown.

  


1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users