Ah, yes. I saw that Albert had posted the listings for how young Dave Connolly got on in the winter Olympics Skeleton (20th! excellent for him), his previous blog entry had me cringe.
It was another case of expecting a language to perform implicit type conversion when assigning it. I was learning C when I found out about this. <float> = <int> / <int>; does not yield the correct answer if you were expecting a floating point answer.
It’s partially to do with the way the language is implemented and partially to do with the KISS principle. What you are doing is essentially performing two separate operations. A division operation, followed by an assignment operation. The division operation will happen with all the precision of the types that were used, so under the rules, if none of the values are a floating point value then the operation will not use floating point arithmetic. I mean, if you had to convert every integer into a floating point value every time you encountered a mathematical operation just in case the answer is a floating point value you end up making the system very, very slow and potentially likely to cause problems of other types.
Like attempting to make an equality test on floating point numbers. Let’s just say you should never use a direct equality comparison on floating point values, as even if you think the value is 0.0 it may in reality be 0.0000000000001. With the extra precision of floating point numbers comes less accuracy, and to steal someone else’s description, if ints are bricks then floats are more like silly putty.
If you want to use floating point math then at least one of the elements of the operation must be a floating point value. For example:
int a = 1; int b = 2; float c = 0; c = a / b;
Means that c is 0.0, not 0.5, because everything on the right hand side of the operation is an integer
c = (float)a / b;
Would cause c to be 0.5, which is what you wanted. As an aside the initial float c = 0 has an implied type conversion from int to float. It should really have been c = 0.0.
Of course, we can’t forget all the joyous C constant things we had to remember…. <value>U for unsigned, L for long, UL for unsigned long, LL for long long (64 bit anyone). When you’re using C on a predominantly 16 bit programming environment (like the palm platform), then you need to keep reminding yourself, because an int on the palm is only 16bits in size.
oh the joy of it all!