HP-UX Floating-Point Guide
Chapter 3 93
Factors that Affect the Results of Floating-Point Computations
Floating-Point Coding Practices that Affect Application Results
Sample Program: trunc.c
#include <stdio.h>
int main(void)
{
double x;
int i, n;
x = 1.5;
for (i = 0; i < 10; i++) {
n = x;
printf("x is %g, n is %d\n", x, n);
x += 0.1;
}
}
No matter how close the value of x gets to 2.0, C conversion rules require
the fractional part to be truncated. Therefore, the output of the program
is as follows:
xis1.5,nis1
xis1.6,nis1
xis1.7,nis1
xis1.8,nis1
xis1.9,nis1
xis2,nis2
xis2.1,nis2
xis2.2,nis2
xis2.3,nis2
xis2.4,nis2
Many algorithms legitimately require truncation of results to integral
values. One way to avoid the kind of problem illustrated by the preceding
example is to add 0.5 to the result of a floating-point value that must be
assigned to an integer:
n=x+0.5;
Doing this will effectively round the result to the nearest integer (if x is
greater than or equal to 0). Another solution is to call the function rint,
which rounds a double value to the nearest integer:
n = rint(x);
If you use either of these solutions, the program output is
xis1.5,nis2
xis1.6,nis2
xis1.7,nis2
xis1.8,nis2
xis1.9,nis2
xis2,nis2
xis2.1,nis2
xis2.2,nis2
xis2.3,nis2
xis2.4,nis2