소프트웨어/C

int * float 의 관계에 대해서

개발자_이훈규 2015. 7. 30. 15:52

코딩을 하다가 예상과 다른 값이 나와서 이것 저것 찾아보다 보니..

float와 int의 관계에서 문제가 생겼다.


float와 int의 곱에서 float의 값을 유지하기 위해서는,


(int)(int * int * float)의 형태가 되어야한다.

즉, float와 int의 곱을 한 값에서 int로 캐스팅을 하는 것이다.


아래는 그 실험이다.








Result : 

hklee@hklee:~/Dropbox/cpp/testcase/float$ g++ main.cpp ; ./a.out

main.cpp: In function ‘void func1()’:

main.cpp:16:29: warning: format ‘%f’ expects argument of type ‘double’, but argument 2 has type ‘int’ [-Wformat=]

     printf("1/2 = %f\n", 1/2);

                             ^

main.cpp: In function ‘void func2()’:

main.cpp:36:55: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘double’ [-Wformat=]

     printf("sum(int) * scale(float) = %d\n", sum*scale);

                                                       ^

main.cpp:37:62: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘double’ [-Wformat=]

     printf("sum(int) * scale(float) = %d\n", (float)sum*scale);

                                                              ^

main.cpp:40:52: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘double’ [-Wformat=]

     printf("int * int * float = %d(%%d)\n", 5*5*0.5);

                                                    ^

main.cpp:41:66: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘double’ [-Wformat=]

     printf("(float)int * int * float = %d(%%d)\n", (float)5*5*0.5);

                                                                  ^

main.cpp:42:80: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘double’ [-Wformat=]

     printf("(float)int * (float)int * float = %d(%%d)\n", (float)5*(float)5*0.5);

                                                                                ^

main.cpp:46:62: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘double’ [-Wformat=]

     printf("(int)int * int * float = %d(%%d)\n", (int)5*5*0.5);

                                                              ^

1/2 = -0.052041

1/2 = 0

1/2 = 0.500000

1/2 = 0

sum(int) * scale(float) = 5

sum(int) * scale(float) = 0

sum(int) * scale(float) = 0

sum(int) * scale(float) = 5

int * int * float = 0(%d)

(float)int * int * float = 0(%d)

(float)int * (float)int * float = 0(%d)

(int)((float)int * (float)int * float) = 12(%d)


(int)int * int * float = 0(%d)

(int)(int * int * float) = 12(%d)

num = 4.000000

num = 1.000000

num = 0.250000

num = 0.062500

num = 0.015625

num = 0.003906

num = 0.000977

num = 0.000244

num = 0.000061