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 it?

edit: This is not even a matter of integer and float, if I replace int b = 2: float b = 2.0f returns the same stupid result

+6
source share
2 answers

The result of multiplying a float and a int is equal to float . In addition, when switching to printf it will be increased to double . You need the formats %a , %e , %f or %g . The %d format is used to print int types.

Editorial Note: The return value of main must 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 conclusion:

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

Alternatively you can also do

 printf("%d\n", (int)(a*b)); 

and this will print the result you expect (sort of).

You should always explicitly specify the variables according to the format string, otherwise you might see some weird values ​​printed.

+2
source

Source: https://habr.com/ru/post/947072/


All Articles