473,238 Members | 1,791 Online

# 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 21797
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,208 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