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

有帮助吗?

解决方案

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

其他提示

Alternately, you could also do

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

and this would print the result you're (kind of) expecting.

You should always explicitly typecast the variables to match the format string, otherwise you could see some weird values printed.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top