Lesson 2 of 10
Variables and types
- 11 min
- 6 checks
- 3 hints
- Go to task
Goal
Types and integer division
Explanation
In C++ you write each variable's type when you define it, and the variable keeps that type: int lives = 3; is a whole number, double speed = 4.5; is a decimal, char rank = 'S'; is a single character between single quotes, bool alive = true; is true or false, and std::string name = "Layan"; is text between double quotes, which comes from <string>. From this lesson on we'll write std:: explicitly instead of using namespace std;, as most professional programmers do, because it makes clear where each name comes from and keeps a library name from clashing with one of yours.
The type affects the result of a calculation. Divide a whole number by a whole number and the result is a whole number, with the fraction dropped and no warning at all: 7 / 2 is 3, and 45 / 60 * 100 is zero, not 75, because 45 / 60 became zero before the multiplication even started. The fix is to convert one side to a decimal before the division, like this: static_cast<double>(total) / count, or to multiply before you divide. If you convert after the division, as in static_cast<double>(7 / 2), you get 3.0, because the fraction was already gone before the conversion.
std::cout prints a bool as a number, 1 for true and 0 for false, but if you put std::boolalpha before it in the print statement, it prints true or false. A "\n" at the end of a string moves you to a new line, just like std::endl.
Your task
Fix double average(int total, int count) so it returns the average as a decimal: average(45, 6) should give 7.5, not 7. Fix int hpPercent(int hp, int maxHp) so it returns the health percentage as a whole number out of 100: hpPercent(45, 60) should give 75, not zero. Then write bool isLowHp(int hp, int maxHp) so it returns true when the percentage is below 25, and add a third line to main that prints Low HP: true from isLowHp(10, 60).
Checks
6 checks- average(45, 6) returns 7.5, not 7
- average is correct for other values and for negative numbers
- hpPercent(45, 60) returns 75, not zero
- hpPercent is correct for full health, zero and fractions
- isLowHp treats anything below 25% as low, and 25% or more as not low
- All three lines were printed: 7.5, 75% and true