문제

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