Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / Languages / Managed C++ / July 2004

Tip: Looking for answers? Try searching our database.

problem about converting "float" to "int"

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
pango - 04 Jul 2004 15:00 GMT
I write below code in my program:
float f=0.371f;
int i=(int)(f*1000.0f);

I think the result of "i" should be "371",but in fact it is "370",why?How to solve it?
doug mansell - 06 Jul 2004 02:28 GMT
> I write below code in my program:
> float f=0.371f;
> int i=(int)(f*1000.0f);
>
> I think the result of "i" should be "371",but in fact it is "370",why?How to solve it?

If you look at f in your debugger you will see it is actually
0.37099999.  This is the nature of floating point representation.  The
other key thing to note is that float to integer conversions don't
round.  If you want rounding, you write your own.

And, as an exercise in confusion, inspect this with your debugger:

int i2 = (0.371 * 1000.0);

doug.
Ronald Laeremans [MSFT] - 06 Jul 2004 16:41 GMT
Search for "what every programmer should know about floating point" using
your favorite search engine for the classic (and well written) article
describing this and other relevant issues.

Ronald Laeremans
Visual C++ team

>> I write below code in my program:
>> float f=0.371f;
[quoted text clipped - 13 lines]
>
> doug.

Rate this thread:







Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.