Path: utzoo!attcan!uunet!lll-winken!ames!xanth!ukma!uflorida!novavax!hcx1!hcx3!shirono From: shirono@hcx3.SSD.HARRIS.COM Newsgroups: comp.lang.c Subject: Re: Yet another pcc botch Message-ID: <44100018@hcx3> Date: 25 Jan 89 20:10:00 GMT References: <3310@cbnews.ATT.COM> Lines: 53 Nf-ID: #R:cbnews.ATT.COM:3310:hcx3:44100018:000:1705 Nf-From: hcx3.SSD.HARRIS.COM!shirono Jan 25 15:10:00 1989 In article <3310@cbnews.ATT.COM> lvc@cbnews.ATT.COM (Lawrence V. Cipriani) writes: > main() > { > float f, g; > unsigned short u, v; > short s, t; > > u = 250; s = 250; t = 100; v = 100; > f = t - s; g = v - u; > > printf("f = %f, g = %f\n", f, g); > } > > f = -150.000000, g = 65386.000000 > > The correct value for g is -150.000000. Excuse me... Is the correct value of g REALLY -150.00? Recall that both v and u are unsigned short. (v - u) should therefore be evaluated as unsigned short and then converted to float, right? According to K&R, (p. 183), Unsigned integers, declared ``unsigned,'' obey the laws of arithmetic modulo 2^n where n is the number of bits in the representation. According to K&RII, (p. 36), unsigned numbers are always positive or zero, and obey the laws of arithmetic modulo 2^n, where n is the number of bits in the type. So, assuming sizeof(unsigned short) is 2, then arithmetic of unsigned short is done modulo 2^(16), or 65536. In this case, (100 - 250) mod 65536 = -150 mod 65536 = 65386 mod 65536 = 65386 g = 65386.0 QED --Roberto ______________________________________________________________________________ || Internet: shirono@ssd.harris.com Roberto Shironoshita || Harris Corporation || ...!novavax---\ Computer Systems Division || UUCP: ...!uunet-------!hcx1!shirono || ...!mit-eddie-/ ------------------------------------------------------------------------------ DISCLAIMER: The opinions expressed here are my own; they in no way reflect the opinion or policies of Harris Corporation.