Skip to content

Mixing ints and decimals

Read · 1 of 4

Make one side a double

If either side of / is a double, C does decimal division: 17 / 5.0 is 3.4.

With two int variables, cast one: (double) total / count. The cast turns total into a double just for this calculation.

Read this lesson as text

Get the decimal answer when you need it, with a cast.

Make one side a double

If either side of / is a double, C does decimal division: 17 / 5.0 is 3.4.

With two int variables, cast one: (double) total / count. The cast turns total into a double just for this calculation.

Where did the decimals go?

#include <stdio.h>

int main() {
    int total = 7, count = 2;
    double a = total / count;
    double b = (double) total / count;
    printf("%.1f %.1f\n", a, b);
    return 0;
}

What does this print?

  • 3.0 3.5
  • 3.5 3.5
  • 3.0 3.0
Show the answer

3.0 3.5 In a, 7 / 2 is done in ints first (3), then stored as 3.0. In b, total becomes 7.0 before dividing, so the answer is 3.5.

Exercise: Average of three marks

This should print the average of three marks with 2 decimals, but 70 71 71 prints 70.00 instead of 70.67. Fix it.

Exercise: Percentage

Read marks scored and maximum marks (both whole numbers). Print the percentage with 1 decimal and a % sign: 45 60 → 75.0%.

To print a % sign with printf, write %%.