Floating-point types
- C course
- Beginner
- Lesson 14/116
- 4 min
Learn float, double and long double types.
Floating-point types
C has two types for decimals:
float: single precision (usually 4 bytes, ~7 digits)double: double precision (usually 8 bytes, ~15 digits)
The default choice is double for higher precision. With printf you use %f or %lf. Constants like 3.14 are double by default.
Precision and scientific notation
float uses less memory but has lower precision. double uses more memory but is more precise. Prefer double for sensitive values like money or measurements.
For very large or small numbers you can use scientific notation:
double avogadro = 6.022e23;
printf("%e", avogadro);The %e specifier prints the number in exponential form.
Practice Compute the average
Add the line that computes the average and a printf call to the program below. Find the average with avg = (a + b) / 2; and print it with %lf.
Starter code
#include <stdio.h>
int main(void) {
double a = 4.5;
double b = 5.5;
// average = (a + b) / 2 and print with printf
return 0;
}Sample solution
#include <stdio.h>
int main(void) {
double a = 4.5;
double b = 5.5;
double avg = (a + b) / 2;
printf("%lf", avg);
return 0;
}Expected output
5.000000
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is a floating-point type?
- int
- char
- double Correct answer
- void
Explanation: double is a type for decimals.
2 double specifier
printf("Result: ____", 3.14);
printf("Result: %lf", 3.14);
Explanation: %lf is used to print double values.
3 Match the specifiers
| Term | Meaning |
|---|---|
%f |
Float |
%lf |
Double |
%e |
Scientific |
%d |
Integer |