Int and floats

From Teknologisk videncenter
Jump to: navigation, search

C programming

Be careful when mixing floats and ints. Consider this code.

#include <stdio.h>

int main( void ) {
        float f1;
        float f2;
        signed int si1;
        unsigned int ui1;

        si1 = -10;
        ui1 = 100;

        f1 = si1 * ui1;
        printf("f1 = %f\n",f1);
        f2 = (float) si1 * ui1;
        printf("f2 = %f\n",f2);
        return(0);

}

Output from this codesnippet is:

 f1 = 4294966272.000000
 f2 = -1000.000000



Links