Lesson 28 of 31

Floating-Point Numbers

Floating-Point in C

C has two floating-point types:

TypeSizePrecisionSuffix
float32-bit~7 decimal digitsf literal: 3.14f
double64-bit~15 decimal digitsdefault: 3.14

Always prefer double for mathematical computation — it has far more precision and all <math.h> functions operate on it.

Floating-Point Division

Unlike integers, dividing two doubles gives a real result:

double a = 1.0 / 3.0;
printf("%.6f\n", a);  // 0.333333

Constants in <math.h>

<math.h> defines useful constants:

M_PI     // π ≈ 3.14159265358979
M_E      // e ≈ 2.71828182845905
M_SQRT2  // √2 ≈ 1.41421356237310

Comparing Doubles

Never use == to compare floating-point numbers — rounding errors accumulate:

double a = 0.1 + 0.2;
// a is 0.30000000000000004, not 0.3!
// Use a small epsilon instead:
double epsilon = 1e-9;
if (fabs(a - 0.3) < epsilon) {
    printf("equal\n");
}

Computing with Geometry

double r = 5.0;
double area = M_PI * r * r;  // 78.5398...
printf("%.4f\n", area);      // 78.5398

Your Task

Using double and <math.h>, compute and print:

  1. 1.0 / 3.0 with %.6f
  2. The area of a circle with radius 5.0 (M_PI * r * r) with %.4f
  3. sqrt(2.0) with %.6f
TCC compiler loading...
Loading...
Click "Run" to execute your code.