Guys,
I am having a problem with float division using PK51. I was wondering if anyone could explain this or has seen it before.
I have a float, and want to divide it by 36000. If I do this directly, I get strange results, even -ve numbers although all the variables are +ve.
accrued_seconds =(total_accrued_seconds/36000);
Both variables are floats, however, if I do the following
accrued_seconds = (unsigned long)(total_accrued_seconds/10); accrued_hours = (float)(accrued_seconds/3600);
I get the correct result. For some reason that I don't understand using too big a divisor in the first code causes an error but not a two step as in the second. I have also tried the two step without the cast to an unsigned long and I get the errored result.
I tired the same thing on GCC on a PC and of course it works fine.
Any clues anyone?
Cheers,
Dirk
What happens if you write the constant as 36000u? Remember that a 16-bit signed integer only stores positive values up to 32767.
Another alternative - what happens if you write 36000.0?
Thanks Per,
Both solutions work. I hadn't appreciated that the constant value would work that way and be created as a 16 bit signed value.
Thanks for spotting that.
Remember that the 'C' programming language basically assumes that everything is an int unless explicitly specified otherwise.
Also, int defaults to signed.
Do you have all warnings enabled for the compiler?
It is bad form if the Keil compiler (with all warnings enabled) do not generate a warning about out-of-range integers either generating an incorrect/unexpected result or being promoted to long.
It isn't a bug not to warn, but I would consider contacting Keil support and report it as a bug anyway.
Yes, I have all warnings on and there is absolutely nothing flagged by the compiler.
I will send this in to Keil and see what they say.
I don't think it should be issuing a warning in this case. Surely the constant 36000 should be interpreted correctly and silently as signed long, converted to float prior to the division and the answer should be correct? Unless I'm in 'missing the blindingly obvious' mode today this seems wrong.
To the OP: can you tell us what value you actually do get when you run the original code?
"Unless I'm in 'missing the blindingly obvious' mode today this seems wrong."
Indeed. A decimal integer constant's type is the first from the list of 'int', 'long int', 'long long int' (C99) in which its value can be represented.
Exactly. In C90 (aka ANSI C), the list would be 'int', 'long int', 'unsigned long int'. Apparently, Keil's C51 compiler doesn't follow the C90 standard in this case. I cannot think of a good explanation why.
Maybe it depends on whether Integer Promotion is enabled or not...
View all questions in Keil forum