typestar

Floating point in C

float, double, and why you never compare them with equals.

#include <math.h>
#include <stdio.h>

int nearly(double a, double b, double tolerance) {
    return fabs(a - b) < tolerance;
}

void floats(void) {
    double sum = 0.1 + 0.2;
    printf("%.20f\n", sum);
    printf("equal: %d, nearly: %d\n", sum == 0.3, nearly(sum, 0.3, 1e-9));

    float single = 1.0f / 3.0f;
    printf("%.7f %.15f\n", single, sqrt(2.0));
    printf("%.0f %.0f\n", floor(2.7), ceil(2.1));
}

How it works

  1. double is the default for a literal like 1.5.
  2. Rounding means 0.1 + 0.2 is not exactly 0.3.
  3. Compare against a tolerance instead.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
382
Tokens
116
Three-star pace
80 tpm

At the three-star pace of 80 tokens a minute, this run takes about 87 seconds.

Type this snippet

Step 5 of 7 in Variables & types, step 5 of 35 in Language basics.

← Previous Next →