c++ float and integer

G

Geky

Why when I multiply a float , for example X10, and than convert it as
an integer the new value is changed?

Example:

float fl = 1.8
int x;

x = int(fl * 10);

x = 17 <<<<<<<< I think this is not correct :)

this happen a lot of time in my code with other float numbers.

is this a bug of VisualC6 or I need a solution?
 
T

TB

Geky sade:
Why when I multiply a float , for example X10, and than convert it as
an integer the new value is changed?

Example:

float fl = 1.8
int x;

x = int(fl * 10);

x = 17 <<<<<<<< I think this is not correct :)

this happen a lot of time in my code with other float numbers.

is this a bug of VisualC6 or I need a solution?

Most likely because (1.8f * 10) can't be perfectly represented.
Internally it might be 17.9999999999 which when you truncate it
to an integer becomes 17.
 
S

Shark

Geky said:
Why when I multiply a float , for example X10, and than convert it as
an integer the new value is changed?

Apart from being a VC question (which you should ask in a relevant
group) consider what happens when you convert from a float to an int. A
float can be represented in many ways, and generally the convention is
to use IEEE754-1985 standard.

Lets say you have a number 32 bits long, and you try jamming those 32
bits into 8 bits. What happens? 24 bits are left out!!!! So 3/4 times
information about your float number is lost! Makes sense? No wonder you
are getting a wrong answer.
 
M

Mike Wahler

Geky said:
Why when I multiply a float , for example X10, and than convert it as
an integer the new value is changed?

Example:

float fl = 1.8
int x;

x = int(fl * 10);

std::cout << std::fixed << fl << '\n';
std::cout << std::fixed << fl * 10 << '\n';

x = 17 <<<<<<<< I think this is not correct :)

this happen a lot of time in my code with other float numbers.

is this a bug of VisualC6
No.

or I need a solution?

http://docs.sun.com/source/806-3568/ncg_goldberg.html

-Mike
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top