...

/

Solution Review: Implement a Calculator Class

Solution Review: Implement a Calculator Class

This review provides a detailed analysis to solve the 'Implement a Calculator Class' challenge.

We'll cover the following...

Solution

Press + to interact
class Calculator {
// Class fields
private double _num1;
private double _num2;
// Default Constructor
public Calculator(double num1, double num2) {
this._num1 = num1;
this._num2 = num2;
}
// Addition Method
public double Add() {
return this._num1 + this._num2;
}
// Subtraction Method
public double Subtract() {
return this._num2 - this._num1;
}
// Multiplication Method
public double Multiply() {
return this._num1 * this._num2;
}
// Divison Method
public double Divide() {
return this._num2 / this._num1;
}
}
class Demo {
public static void Main(string[] args) {
Calculator calc = new Calculator(10, 94);
Console.WriteLine("Addition:" + calc.Add());
Console.WriteLine("Subtraction:" + calc.Subtract());
Console.WriteLine("Multiplication:" + calc.Multiply());
Console.WriteLine("Division:" + calc.Divide());
}
}

Explanation

  • Line 4-5: We have implemented the Calculator class which has the fields _num1 and _num2.

  • Line 8-11: In the constructor, we have initialized both fields to num1 and num2.

  • Line 14-16: Implemented Add(), a method which returns the sum of two numbers, i.e., num1+num2num1 + num2 ...