Skip to content
FollowtheDamnCode

Type Conversion and Casting

Why 5 / 2 is 2, and how to get 2.5.

4 minute read

Big idea

The types of the values decide what an operator does. 5 / 2 is 2, but 5.0 / 2 is 2.5.

The idea

When both sides of / are int, C does integer division and drops the fraction. If either side is a float or double, C converts the other one too and keeps the fraction:

ExpressionTypesResult
5 / 2int / int2
5.0 / 2double / int2.5
5 / 2.0int / double2.5

That automatic change of type is called implicit conversion. C always converts toward the type that can hold more — int becomes double, never the other way.

Casting: converting on purpose

When both values are int variables, you can't just add .0. Instead, cast one of them — write the type you want in brackets in front of it:

int total = 7, count = 2;
double average = (double) total / count;   // 3.5

(double) total means "treat total as a double here". Now the division keeps its fraction.

Predict: where does the .5 go?
#include <stdio.h>

int main(void) {
    int total = 7, count = 2;
    double a = total / count;
    double b = (double) total / count;
    printf("%.1f %.1f\n", a, b);
    return 0;
}
What does it print? Show the answer
3.0 3.5

Run and edit it in the app.

Look at a: storing the answer in a double doesn't help. total / count is already 3 before it's stored — the fraction was lost in the division itself.

Going the other way

Casting a decimal to int chops off the fraction — it doesn't round:

int x = (int) 3.99;   // 3
int y = (int) -3.99;  // -3

%.1f in printf prints a double with one digit after the point; %.2f gives two.

Fix the bug: the average of 3 test scores
#include <stdio.h>

int main(void) {
    int a = 70, b = 85, c = 90;
    double average = (a + b + c) / 3;
    printf("%.2f\n", average);
    return 0;
}
output
81.67

Run and edit it in the app.

Watch it

Think of it like

A calculator that only shows whole numbers. Ask it 5 ÷ 2 and it shows 2. Casting is switching it into a mode that shows decimals — but you have to switch before you press ÷.

🕷️ Spidey-sense: I once split a $5 pizza between 2 of us with integer math. We each paid $2 and the pizza place was out 50 cents. Cast before you divide — Aunt May taught me to pay my share.

Key terms

  • Integer division — / between two ints: the fraction is dropped.
  • Implicit conversion — C changing a value's type automatically, e.g. int to double in 5.0 / 2.
  • Cast — Converting on purpose: (double) x.

Check yourself

What does 7 / 2 give when both are ints?

Which gives 3.5?

What is (int) 4.99?