i have some problem about integer conversion Pls help! 1. what will happen if i make a float variable to the integer or char? e.g: float a=2.02342; int x; char y; x=a; y=a; what will happen ? x=? y=? 2. in case of the data will be affected in change variable type. How can i convert the integer parts of the float to int? e.g a=2.35325325 Y=a; how can i change a to 2? if a=2.655775 y=a; how can i change a to 3? thx 2.
When a value of floating type is converted to integral type, the fractional part is discarded; if the resulting value cannot be represented in the integral type, the behaviour is undefined.
y = (int)(A + 0.5);
i have write a simple program to test it #include "stdio.h" int x=20; float y=23.5; void main(){ printf("x=%f\n",x); x=y; printf("x=%f\n",x); printf("y=%f\n",y); } and the result is x=20 x=0 <--- loss data? y=23.5
thx so much
That test program is seriously buggy. The %f format specifier in the first two printf() calls must be changed to %d or a similar one. The fact that the first printf() still works smells of an over-optimization, or pure luck.