Float to Int not quite right? MikroC Compiler

Status
Not open for further replies.

5uco

Member
Hi Folks

Not experienced on float, just tried this:


Code:
float           number1;
unsigned int    number2;
float           answer;
int             answer2;
//
void main()
{
     number1 = 0.005;
     number2 = 1000;
     do
       {
       answer  = number1 * number2;
       answer2 = answer ;
       number2 = number2 + 1000;
       }
 while (1);
}

.. and I get a wrong answer value in answer2 variable. It's always 1 less.

So, maybe it sees say'3' as 2.999999999 etc.etc ??

I can get around it by always adding '1' but that does seem rather inelegant. So, where am I wrong ??

Dave
 

Attachments

  • MikroC Float.JPG
    41.3 KB · Views: 594
Float to int is ALWAYS the floor value ie 2.3 = 2... 2.9 = 2 2.000001 = 2 and 2.99999999999 = 2.

You may want tio use the function ceil()... But I don't know if you have it in mikroC... ceil() returns the number rounded up... floor() returns a number rounded down.
 
Or you can use round() if it has it, but the standard way is to add 0.5 before the implicit floor() conversion. This way 2.0000001 to 2.499999 will still give you 2, but 2.5 to 2.9999 to 3.49 will give you 3.

ETA: obviously doesn´t work for negative numbers, you need to substract 0.5 there.
 
Last edited:
Hi Kubeek

No round() in MikroC it seems.

The advise from Ian works fine ..

As an aside there is one heap of difference between the compiled ( same) code in MikroC and HTC ..

MikroC ---- ROM 1038 RAM 26
HTC ---- ROM 1350 RAM 45


Thanks to both of you

Dave
 
Yes but for 2.0001 ceil will give you 3 which is obviously not correct. If you add the 0.5 or -0.5 for negative numbers first you will get a properly rounded result just with the implicit floor conversion.
 
Hi Kubeek

Apologies for the poorly composed reply from me ..

Yes, indeed I found that your advise was correct.

Dave
 
If you prefer. I just thought the goal was to add or subtract 0.5 from the float vlaue to round it.

Generally I would do that, and the data type conversion elsewhere as that is really part of the display function. But then I guess so is the round() operation...
 
I do prefer, as to have a round function that doesn't is, well, wrong.

Mike.
 
Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…