Multiply and divide
- C++ course
- Beginner
- Lesson 21/116
- 6 min
Add multiplication, division and the divide-by-zero check.
Multiply and divide
Now we will fill in the multiply and divide methods. Multiplication uses the * operator, division uses /.
The multiply body should be return a * b;. The divide body should be return a / b;. With these small changes, all four operations of the calculator work.
Because we use double, decimal results are preserved in division: 7.0 / 2.0 = 3.5. If we used int, the result would be 3 (truncated).
Division with double
In C++, division depends on the types of the operands. Dividing two int values gives an int: 7 / 2 = 3. Dividing two double values keeps the decimal: 7.0 / 2.0 = 3.5.
Since the calculator parameters are double, division works with decimals. Calling calc.divide(20, 4) returns 5; calling calc.divide(7, 2) returns 3.5.
The result is a single double value that can be printed with std::cout. In the next lesson we will handle division by zero.
Practice Fill in multiply and divide
Change the multiply method body to return a * b; and the divide method body to return a / b;. The main already calls calc.multiply(6, 4); the output must be 24.
Starter code
#include <iostream>
class Calculator {
public:
double add(double a, double b) { return a + b; }
double subtract(double a, double b) { return a - b; }
double multiply(double a, double b) { return 0; }
double divide(double a, double b) { return 0; }
};
int main() {
Calculator calc;
// Fill in multiply and divide with real arithmetic
std::cout << calc.multiply(6, 4) << std::endl;
return 0;
}Sample solution
#include <iostream>
class Calculator {
public:
double add(double a, double b) { return a + b; }
double subtract(double a, double b) { return a - b; }
double multiply(double a, double b) { return a * b; }
double divide(double a, double b) { return a / b; }
};
int main() {
Calculator calc;
// Fill in multiply and divide with real arithmetic
std::cout << calc.multiply(6, 4) << std::endl;
return 0;
}Expected output
24
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match operators
| Term | Meaning |
|---|---|
+ |
Addition |
- |
Subtraction |
* |
Multiplication |
/ |
Division |
2 Which is the correct body for the multiply method?
- return a + b;
- return a * b; Correct answer
- return a / b;
- return 0;
Explanation: The multiply method returns a * b.
3 Multiply body
double multiply(double a, double b) { return ____; }
double multiply(double a, double b) { return a * b; }
Explanation: The multiply method returns a * b.