|
안녕하세요 :-)
float이나 double형이 아주 정확하지 않다는(?) 소문은 듣고있었으나 지나가는 글로 보기에 0.00000001 * 10000000 등을 하면 1이 아니라는식의.. 저와는 상관이 없는 이야기 일줄로만 알고있었는데. 오늘 이것땜에 골치를 썩고 있네요 ㅠ.ㅠ
예) #include <stdio.h> #include <functional> #include <vector> #include <algorithm>
int main() { int st=0,ed=10; unsigned int cnt=100; double step;
step = (ed-st)/(double)cnt;
printf("\n%f",step); /* 0.100000 으로 출력됨 */ printf("\n%f",((ed-st)/step)); /* 100.000000 으로 출력됨 */ printf("\n%d",(unsigned int)((ed-st)/step)); /* 99로 출력됨 */
if( ((unsigned int)((ed-st)/step)) == 100 ) { printf("100맞다"); /* 출력 안됨 */ } return 0; }
이런데요. 0.1 단위인데도 이상하게 99로 출력이 되네요. 100.000000 -> 형변환 -> 99 라는 소린데. 제가 무언가 착각하고 있는거 같기도 하구요 그냥 printf("%d", (unsigned int)(100.0)) 이런건 100으로 잘 출력이 되구요. 무슨 현상인지 꼭좀 조언 부탁드립니다 ㅠ.ㅠ
저의 무지를 깨우쳐 주실분을 간절히 기다립니다. ㅠ.ㅠ
추가합니다- 우어 -_-; 제가 Borland C++ builder 6.0 / 공개된 볼랜드 컴파일러 5.5 / 비쥬얼 스튜디오 2003 에서 같은 소스로 컴파일을 해봤는데. 볼랜드 계열은 99로 나오고, 마소계열은 100으로 나오는군요 주로 쓰는게 볼랜드 계열이라.. ㅠ.ㅠ (혹이 이것에 대해 아시는분 조언 바랍니다 ㅠ.ㅠ)
추가합니다 -
------------------------------------------------------- #include <stdio.h>
void showFtoB(double value) /* 그냥 비트로 보여주는 함수 */ { unsigned int *pt = (unsigned int *)&value; printf("\n"); for(int i=0;i<32;++i) { if(i%8==0) printf("|"); printf("%d",(((1<<i)&(*pt))>>i)); } ++pt; for(int i=0;i<32;++i) { if(i%8==0) printf("|"); printf("%d",(((1<<i)&(*pt))>>i)); } printf("\n"); }
int main() { int st=0,ed=10; unsigned int cnt=100; double step,x;
step = (ed-st)/(double)cnt;
x = (ed-st)/step;
showFtoB(x); showFtoB((ed-st)/step); showFtoB(100.0); printf("\n%d",(unsigned int)x); printf("\n%d",(unsigned int)100.0); printf("\n%d",(unsigned int) ((ed-st)/step) ); if ( (unsigned int)x == 100 ) printf("\n아싸 난 100"); if ( ((unsigned int)((ed-st)/step)) == 100 ) printf("\n아싸 또 100");
return 0; }
----결과 ---------------------------------------------;
---------- Excute ---------- Borland 계열 |00000000|00000000|00000000|00000000|00000000|00000000|10011010|00000010
|00000000|00000000|00000000|00000000|00000000|00000000|10011010|00000010
|00000000|00000000|00000000|00000000|00000000|00000000|10011010|00000010
100 100 99 아싸 난 100
---------- Excute ---------- MS 계열 |00000000|00000000|00000000|00000000|00000000|00000000|10011010|00000010
|00000000|00000000|00000000|00000000|00000000|00000000|10011010|00000010
|00000000|00000000|00000000|00000000|00000000|00000000|10011010|00000010
100 100 100 아싸 난 100 아싸 또 100
음 이런 결과가 나왔는데. 이걸 어떻게 해석해야 할지? printf문이 문제인건지.
왜 변수에 담았다가 형변환을 하면 잘되면서. 그냥하면 안나오는지 알수가 없네요 ㅠ.ㅠ
showFtoB 는 왜 저따구로 만들었냐 태클은.. ㅠ.ㅠ 하지 말아주세요. 급한김에.. |