Codiqo

Learn C# · lesson 9 of 61 · about 9 minutes

Project: Critical Hits

Read a critical-hit multiplier, turn it into whole damage with a cast, and show the battle on a lined-up scoreboard.

What you'll learn

  • Combine input, arithmetic and interpolation
  • Turn a double into an int with a cast
  • Line up columns with alignment

The plan

A critical hit multiplies the damage, say by 1.5. This lesson's project:

1. Reads the multiplier as a double
2. Works out the damage and turns it into a whole number
3. Takes it off the Slime's HP
4. Prints a scoreboard with the numbers lined up

Casts and columns

HP is a whole number, but 3 × 1.5 is 4.5. A cast, (int)(damage * crit), turns it into an int by dropping the decimals: 4.

In interpolation, a comma sets a width. {heroHp,4} fills 4 characters, with spaces in front, so numbers line up on the right. {"Hero",-6} fills 6 with spaces after, so words line up on the left.

A scoreboard

double crit = double.Parse(Console.ReadLine() ?? "1");
int strike = (int)(7 * crit);
Console.WriteLine($"Critical x{crit}: {strike} damage");
Console.WriteLine($"{"Hero",-6}{30,4} HP");
Console.WriteLine($"{"Slime",-6}{12 - strike,4} HP");

Output

Critical x1.5: 10 damage
Hero    30 HP
Slime    2 HP

Tip

(int)7 * 1.5 is still a double: the cast only applies to the 7. Put the whole sum in brackets: (int)(7 * 1.5).

Now try it yourself

This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.