Chief Delphi

Chief Delphi (http://www.chiefdelphi.com/forums/index.php)
-   Programming (http://www.chiefdelphi.com/forums/forumdisplay.php?f=51)
-   -   Converting floating point to integers (http://www.chiefdelphi.com/forums/showthread.php?t=33561)

logicalhippo 28-01-2005 20:31

Converting floating point to integers
 
I'm having a little problem with converting floating point values to integers. if I do something like this:

float f = 245.56;
int i;
i = (int)f;
printf("%d\n", i);

the output will be 0. Can anyone explain this problem? Do I need an explicit conversion? If so, where could I find documentation on it?

colt527 28-01-2005 22:40

Re: Converting floating point to integers
 
This SHOULD make no difference, but sometimes code is like that. Dont declare a new variable for it. Just do:

float f = 245.56;
printf("%d\n", (int)f);

I've never had a problem doing it that way *shrugs* ... hope it works.

EDIT: actually, i think if you wanted to do it you way, just cast it again inside the printf, like this:

float f = 245.56;
int i;
i = (int)f;
printf("%d\n", (int)i);

I vaguely remember something about printf that if you dont cast inside the function, it does some weird things. Hope one of those works!

Chriszuma 28-01-2005 22:52

Re: Converting floating point to integers
 
if your code is perfectly correct, there's a pretty good chance that it's just the controller using some sort of bistromath. We've come to the conclusion that it just sucks at computing floating point numbers. You're best off making sure that all numbers are computed in integer form.

Mark McLeod 29-01-2005 12:10

Re: Converting floating point to integers
 
Quote:

Originally Posted by logicalhippo
float f = 245.56;
int i;
i = (int)f;
printf("%d\n", i);

the output will be 0.

That code works fine for me. There's something else at work here.


All times are GMT -5. The time now is 19:33.

Powered by vBulletin® Version 3.6.4
Copyright ©2000 - 2017, Jelsoft Enterprises Ltd.
Copyright © Chief Delphi