468,512 Members | 1,535 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,512 developers. It's quick & easy.

conversion from 'int' to 'float', possible loss of data ??

Expand|Select|Wrap|Line Numbers
  1. int a=10;
  2. int b=3;
  3.  
  4. float c;
  5. c=a/b;
  6.  
  7. cout << c << endl;
if, in my program, the int type for a and b is a must (according to the return), performing operation on a & b results in float type of c.

From msvc++, a message "warning C4244: '=' : conversion from 'int' to 'float', possible loss of data" is resulted. how to solve? the c variable printed out to the screen is 3, but not 3.3333333333333............. !
Apr 6 '08 #1
2 19526
Laharl
849 Expert 512MB
Because neither a nor b is a float or double, but are instead both integers, integer division is done, so the remainder is jettisoned and the whole number is all that can be stored. Either declare one of a or b as float/double or use a cast, eg ((float) a)/b. Don't try to cast the result, eg (float)(a/b), since that will just cast 3 to a float, 3.0.
Apr 6 '08 #2
weaknessforcats
9,207 Expert Mod 8TB
[quote=Laharl]
Because neither a nor b is a float or double, but are instead both integers, integer division is done, so the remainder is jettisoned and the whole number is all that can be stored. Either declare one of a or b as float/double or use a cast, eg ((float) a)/b. Don't try to cast the result, eg (float)(a/b), since that will just cast 3 to a float, 3.0.
[quote]

Not entirely correct.

a and b are int and c is a float. c/a requires an automatic conversion. In this case, the int a is converted to a temporary float, the division is done using float and the result is a float. See K&R page 198 A6.5.

The warning is due to the fact that a float has only six significant figures whereas an int can have more. If it does, then accuracy is lost.

In general, you cannot convert an integer to floating point without possibke losing data. Also, you cannot convert from floating point back to integer without losing the deceimal places, so you get a warning again.

My advice is to stick with either all integer or all floating point. If you decide on floating point, then use double throughout unless you can write diwn on paper the precise reason you can't do this. In this respect your advice is correct.
Apr 7 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

2 posts views Thread by Brian van den Broek | last post: by
4 posts views Thread by Simon Cheng | last post: by
1 post views Thread by Josué Andrade Gomes | last post: by
24 posts views Thread by Rajesh S R | last post: by
8 posts views Thread by d major | last post: by
3 posts views Thread by yxxxxy | last post: by
reply views Thread by NPC403 | last post: by
1 post views Thread by fmendoza | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.