Lesson 2 of 10
Types and conversions
- 12 min
- 5 checks
- 3 hints
- Go to task
Goal
The int, double and decimal types, and integer division
Explanation
In C# you set each variable's type when you declare it, and the type never changes after that. You use int lives = 3; for whole numbers, double speed = 4.5; for numbers with a fractional part, decimal price = 19.99m; for money, bool isAlive = true; for true or false, string name = "Layan"; for text, written between double quotes, and char grade = 'A'; for a single character, written between single quotes. A string is a sequence of characters, so its first character is name[0], and that character's type is char. With var, the compiler works out the type from the value, and the type is still fixed from then on.
The most common mistake here is that dividing an integer by an integer gives an integer and silently drops the fraction, so 7 / 2 is 3. That's why you convert one side to double before dividing: (double)7 / 2 is 3.5. (double)(7 / 2), on the other hand, gives 3, because the integer division happened first and the fraction was lost before the conversion. Casting a floating-point number to an int drops the fraction instead of rounding, so (int)7.9 is 7, while Convert.ToInt32(7.9) rounds to 8.
Math.Round(x, 2) rounds a number to two decimal places. We use decimal for money because double stores fractions in binary and can't hold 0.1 exactly, so even 0.1 + 0.2 == 0.3 is false, while decimal keeps the decimal places exactly as you write them. The letter m after a number makes it a decimal. C# won't mix the two types on its own: if price is a decimal, then price * 1.15 is a compile error, and the right way to write it is price * 1.15m.
Your task
Fix Average(points, games) so it returns the average as a floating-point number rounded to two places: someone who scored 47 points in 6 games averages 7.83, not 7. Then complete WholeCoins(gold) to return the number of whole coins by converting to int, PriceWithTax(price) to return the price after adding 15% tax, rounded to two places, and Initial(name) to return the first character of the name.
Checks
5 checks- Average(47, 6) is 7.83, not 7
- Average(10, 4) is 2.5 because the conversion comes before the division
- WholeCoins drops the fraction instead of rounding, so 7.9 becomes 7
- PriceWithTax adds 15% tax with decimal precision and rounds to two places
- Initial returns the first character as a char