Answer to Question #219123 in C++ for Jonas

Question #219123

Create a class called myMath. This class only contains one basic data type (float x). Your class should mimic the +,-,*,/ function in a basic data type. In other words, you need to provide the basic math operations for the objects created under myMath.


main()

{

  myMath m1(10),m2(2),m3; //you can change 10 and 2 to any value to test your code.

m3 = m1 + m2;

  cout <<"\nAddition: "<< m3.getX(); //output is 12

  m3 = m1 - m2;

  cout <<"\nSubtraction: "<< m3.getX(); //output is 8

  m3 = m1 * m2;

  cout <<"\nMultiplication: "<< m3.getX(); //output is 20

  m3 = m1 / m2;

  cout <<"\nDivision: "<< m3.getX(); //output is 5

}


1
Expert's answer
2021-07-20T17:04:13-0400
#include <iostrema>

using namespace std;

class myMath {
public:
  int x;
public:
  myMath(int x) {
    this->x=x;
  }
};

myMath operator+ (const myMath &a, const myMath &b) {
  return myMath(a.x+b.x);
}

myMath operator- (const myMath &a, const myMath &b) {
  return myMath(a.x-b.x);
}

myMath operator* (const myMath &a, const myMath &b) {
  return myMath(a.x*b.x);
}

myMath operator/ (const myMath &a, const myMath &b) {
  return myMath(a.x/b.x);
}

int main() 
{
  myMath m1(10), m2(2), m3;
  
  m3 = m1 + m2; cout <<"\nAddition: "<< m3.getX();
  m3 = m1 - m2; cout <<"\nSubtraction: "<< m3.getX();
  m3 = m1 * m2; cout <<"\nMultiplication: "<< m3.getX();
  m3 = m1 / m2; cout <<"\nDivision: "<< m3.getX();

  return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS