← The C Language Lesson 9 of 77 · 10 XP

Type conversion

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

C converts types in expressions by itself, and not always the way you expect. The main trap is integer division:

int a = 7, b = 2;
printf("%d\n", a / b);         // 3 — the fractional part is dropped
double r = a / b;              // 3.0! the division was integer, and only then did the result become a double

For the division to be fractional, at least one operand must be fractional. That's what an explicit cast is for:

double r = (double)a / b;      // 3.5

The implicit conversion rules, briefly:

  • in an expression with int and double, the int becomes a double;
  • when you assign a fractional value to an integer variable, the fractional part is dropped (not rounded): int x = 3.99; → 3;
  • in arithmetic, char and short are first turned into int.

The remainder operator % works only with integers.

Task. Read a total score (a whole number) and the number of exams (a whole number). Print the average score with two decimal places.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.