A cast asks C to treat a value as another type for a specific expression.

cast `(double)total` converts `total` before the division runs.
integer division Without a cast, dividing two integers keeps only the integer part.

Casts

total
casts.c
Replay: real traced execution (multi-file project)
#include <stdio.h>

int main(void) {
    int total = 7;
    int count = 2;
    double average = (double)total / count;

    printf("average=%.1f\n", average);
    return 0;
}
#include <stdio.h>

int main(void) {
    int total = 9;
    int count = 2;
    double average = (double)total / count;

    printf("average=%.1f\n", average);
    return 0;
}
#include <stdio.h>

int main(void) {
    int total = 11;
    int count = 2;
    double average = (double)total / count;

    printf("average=%.1f\n", average);
    return 0;
}
  1. total ← 7, count ← 2, average ← 3.5

    3int main(void) {4    int total→ 7 = 7; //@total=9, 115    int count→ 2 = 2;6    double average→ 3.5 = (double)total7 / count2;78    printf("average=%.1f\n", average3.5);9    return 0;10}
    outputaverage=3.5
  1. total ← 9, count ← 2, average ← 4.5

    3int main(void) {4    int total→ 9 = 9;5    int count→ 2 = 2;6    double average→ 4.5 = (double)total9 / count2;78    printf("average=%.1f\n", average4.5);9    return 0;10}
    outputaverage=4.5
  1. total ← 11, count ← 2, average ← 5.5

    3int main(void) {4    int total→ 11 = 11;5    int count→ 2 = 2;6    double average→ 5.5 = (double)total11 / count2;78    printf("average=%.1f\n", average5.5);9    return 0;10}
    outputaverage=5.5

Follow the Average

  1. total starts at 7.
  2. count is 2.
  3. (double)total makes the division use a fractional result.
  4. average = 7 / 2 as a double becomes 3.5.
  5. The program prints average=3.5. | total | count | average | | --- | --- | --- | | 7 | 2 | 3.5 | | 9 | 2 | 4.5 | | 11 | 2 | 5.5 |

Exercise: casts.c

Reproduce average=3.5, then use total 9 and 11 to predict each average.