Conversion, rounding, and truncation

Tom Cunningham tomc at oakhill.UUCP
Sat Nov 1 03:01:23 AEST 1986


Well, my query about expression sequencing generated so much excitement
and discussion (and some dross), I thought I'd throw another catalytic
cookie into the ring.  Here is a C code fragment:

	double d;
	long l;
	float f;
	double pow();

	d = pow(2.0,3.0);
	l = d;
	printf("d = %f, l = %ld\n", d, l);
	f = d;
	l = f;
	printf("f = %f, l = %ld\n", d, l);

The output from code generated by the Sun 3 compiler (4.2BSD), Microsoft C,
and VAX VMS C is:

	d = 8.000000, l = 8
	d = 8.000000, l = 8

Output from a Unix SYSV compiler is:

	d = 8.000000, l = 7
	d = 8.000000, l = 8

Now, K&R clearly state on pg. 42 that float to int causes truncation of
any fractional part, and I assume this applies to the double-to-long case
as well.  Moreover, they say that double is converted to float by
rounding, which I guess would explain the second SYSV output line.

What I don't understand is why the formatting routines appear to round
the floating point number, since it looks like the pow() in the SYSV
implementation returns something not quite 8.0.  Am I missing something
here?  If this has already been discussed ad nauseum, someone please
clue me.

Tom Cunningham     "Good, fast, cheap -- select two."
USPS:  Motorola Inc.  6501 William Cannon Dr. W.  Austin, TX 78735-8598
UUCP:  {ihnp4,seismo,ctvax,gatech}!ut-sally!oakhill!tomc
Phone: 512-440-2953



More information about the Comp.lang.c mailing list