Learn C · lesson 8 of 60 · about 9 minutes
Project: Size Converter
Turn the report's free space into MiB and photos with casts, so nothing is lost to integer division.
What you'll learn
- Combine input, constants and arithmetic
- Convert between types with casts
- Format decimal output
The plan
Your report says Free: 4096 KiB, but people think in MiB, and in how many photos still fit. This lesson's converter:
1. Names the conversion with #define KIB_PER_MIB 1024
2. Turns KiB into MiB, keeping the decimals
3. Counts how many 2.5 MiB photos fit, as a whole number
Casts
free_kib / KIB_PER_MIB divides two ints, so the decimals are thrown away. A cast changes a value's type: (double)free_kib is the same number as a double, so the division keeps its decimals.
(int) works the other way: (int)1.8 is 1. It drops the decimals, without rounding.
A converter
#include <stdio.h>
#define KIB_PER_MIB 1024
int main(void) {
int kib;
scanf("%d", &kib);
printf("%d KiB is %d MiB\n", kib, kib / KIB_PER_MIB);
printf("%d KiB is %.2f MiB\n", kib, (double)kib / KIB_PER_MIB);
printf("Songs of 3.5 MiB: %d\n", (int)(kib / 1024.0 / 3.5));
return 0;
}Output
5000 KiB is 4 MiB
5000 KiB is 4.88 MiB
Songs of 3.5 MiB: 1Tip
(double)(kib / 1024) is too late: the brackets make the int division happen first. Cast the value before you divide.
Now try it yourself
This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.