C/C++ Arena

Step 6 of 6

Put it together

Time to put the module together and write a calculation from scratch. Here's how to approach a small task like this, which is the same process you'll use for much bigger ones:

  1. Read what the output must be, character by character.
  2. Name the values you need. What goes into the answer? Give each intermediate result its own variable with a clear name.
  3. Choose types. Counts and sums of whole numbers are int. Averages and ratios are usually double.
  4. Watch for integer division. If you divide two ints and want decimals, cast one side.
  5. Print with the right specifiers: %d for int, %.2f for a double with two decimals.

Here's a similar calculation, fully worked:

#include <stdio.h>

int main(void) {
    int quiz1 = 18;
    int quiz2 = 15;
    int quiz3 = 19;
    int quizzes = 3;
    int total = quiz1 + quiz2 + quiz3;
    double average = (double)total / quizzes;
    printf("Total points: %d\n", total);
    printf("Average: %.2f\n", average);
    return 0;
}
Total points: 52
Average: 17.33

Notice total is computed once and then reused for both lines. Storing intermediate results in well-named variables makes code easier to read and to check.

Your turn: a player's ADR (average damage per round) is total damage divided by rounds played. Given the variables below, print:

Total damage: 2090
ADR: 83.60

Total damage is the sum of the three halves' damage (it's a long match: first half, second half, overtime).

Previous: Prefix vs postfix ++