Search code examples
cintegeroperation

How to multiply float with integers in C?


When I execute this code it returns me 1610612736

void main(){
float a=3.3f;
int b=2;
printf("%d",a*b);
}

Why and how to fix this ?

edit : It's not even a matter of integer and float, if i replace int b=2: by float b=2.0f it return the same silly result


Solution

  • The result of the multiplication of a float and an int is a float. Besides that, it will get promoted to double when passing to printf. You need a %a, %e, %f or %g format. The %d format is used to print int types.

    Editorial note: The return value of main should be int. Here's a fixed program:

    #include <stdio.h>
    
    int main(void)
    {
        float a = 3.3f;
        int b = 2;
        printf("%a\n", a * b);
        printf("%e\n", a * b);
        printf("%f\n", a * b);
        printf("%g\n", a * b);
        return 0;
    }
    

    and its output:

    $ ./example 
    0x1.a66666p+2
    6.600000e+00
    6.600000
    6.6