Step 2
Numbers and maths
Do arithmetic with ints and doubles, avoid integer division and convert degrees to radians.
C++ as a calculator
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ - | add, subtract | 7 - 2 | 5 |
* | multiply | 3 * 4 | 12 |
/ | divide | 7.0 / 2 | 3.5 |
% | remainder (ints only) | 7 % 2 | 1 |
The usual order of operations applies, and parentheses group: (1 + 2) * 3 is 9.
ints and doubles
The type matters. When both sides of / are ints, C++ does integer division and throws the remainder away: 7 / 2 is 3, and 90 / 180 is 0. As soon as one side is a double, you get the real answer: 7.0 / 2 is 3.5. This catches everyone out at least once, so when a result is mysteriously 0, look for two ints being divided.
A variable that should never change can be marked const. The compiler then refuses any line that tries to change it:
const double forearm = 0.25; // metres
Maths functions
#include <cmath> brings in std::sqrt(x) (square root), std::pow(x, 2) (powers), std::sin, std::cos and friends. #include <numbers> gives you π as std::numbers::pi. C++ has no ** operator: square a number with x * x or std::pow(x, 2).
Robots measure angles in radians. A full turn is 360°, or radians, so:
Your task
The starter stores the arm's upper arm (0.30 m), forearm (0.25 m) and an angle in degrees.
- Set
reachto the two lengths added together. Use the variables, not the numbers. - Set
angle_radtoangle_degconverted to radians. Mind the integer division. - Set
diagonalto the length of the diagonal across a square table 0.8 m on each side: .
The program prints all three, and the grader reads them from the console.