bhylu.com

Advertisements

C Floating-point Numbers

Calculate an average while keeping binary representation separate from printed decimal places.

How it works

double stores a floating-point approximation, which is useful for measured values with fractions. Many decimal fractions do not have an exact binary representation. Printing two decimal places rounds the display; it does not change the stored value or make equality checks reliable for arbitrary calculations. Convert at the correct stage when integer operands would otherwise select integer division. For exact currency use an explicitly designed representation, such as checked integer minor units, rather than borrowing a measurement example unchanged.

Run it locally

Use a hosted C17 compiler in a separate lab folder. The command assumes a driver named cc; substitute gcc, clang or zig cc as appropriate. C does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed for these C programs.

cc -std=c17 -Wall -Wextra -Wpedantic -Werror floating-measurements.c -o lesson

On Windows, use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Math-library linking differs by toolchain; GCC on many Unix systems needs -lm after the source.

Download the complete C source. File-writing labs must run in an empty private directory, away from existing reports.

Example

C17 · floating-measurements.c

#include <stdio.h>

int main(void) {
    int total_mm = 103;
    int samples = 4;
    double average_mm = (double)total_mm / samples;
    printf("Mean: %.2f mm\n", average_mm);
    return 0;
}

Expected result

Mean: 25.75 mm

The cast converts total_mm to double before division. The other operand is converted by the usual arithmetic rules, so the division retains the fractional part. Without the cast, 103 / 4 would produce the integer 25 before conversion into average_mm. The chosen numbers make this result exactly representable, but most real sensor arithmetic should be judged against a documented tolerance.

For language and library rules, consult the WG14 C working group and its public C11 committee draft, which describes the core facilities used here; C17 incorporates corrections. Check your compiler and runtime documentation for implementation details.

Advertisements