vBulletin Search Engine Optimization
| |||||||
| Register | FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read |
| ||||
| this program print strange result -------------------------------------- #include <stdio.h> #include <stdlib.h> main() { char buffer[100]; char temp[100] = "453.2"; char outdata[100]; double ret; memset(buffer,0x00,sizeof(buffer)); sprintf(buffer,"%%0%d.%df",30,20); sprintf(outdata,buffer,atof(temp)); ret = atof(temp); printf("outdata of ret =%030.20lf\n",ret); printf("ret =%030.20lf\n",ret); printf("outdata =%s\n",outdata); printf("\n"); } ------------------------------------------------------------- result : outdata of ret =000000453.19999999999999000000 ret =000000453.19999999999999000000 outdata =0000000000000000453.2000000000 ------------------------------------------------------------- i think " ret = 0000000453.200000000000000000000 " should print but the result was not , why ? how do i repair this problem... anyone who knows this, teach me !,, i'll so appreciate you bye |
| ||||
| "jcinema" <jcinema@imeritz.com> a écrit dans le message de news:6fe538ec.0311040018.4964c301@posting.google.c om... > this program print strange result > -------------------------------------- > #include <stdio.h> > #include <stdlib.h> > > main() > { > char buffer[100]; > > char temp[100] = "453.2"; > > char outdata[100]; > > double ret; > > > memset(buffer,0x00,sizeof(buffer)); > sprintf(buffer,"%%0%d.%df",30,20); > sprintf(outdata,buffer,atof(temp)); > > > ret = atof(temp); > > printf("outdata of ret =%030.20lf\n",ret); > > printf("ret =%030.20lf\n",ret); > > printf("outdata =%s\n",outdata); > > printf("\n"); > > } > ------------------------------------------------------------- > result : > outdata of ret =000000453.19999999999999000000 > ret =000000453.19999999999999000000 > outdata =0000000000000000453.2000000000 > > ------------------------------------------------------------- > i think " ret = 0000000453.200000000000000000000 " should print > but the result was not , why ? > > how do i repair this problem... > anyone who knows this, teach me !,, > i'll so appreciate you > > bye Hi, Just because floating point (even double) does not have infinite precision (only 64 bits available). So the atof return the closest value wich fit in 64 bits. The next storable value is probably something like 453.20000000000002 Thats also why you should not use == as a test for floating values. And why you cannot compute 10000000000000000000 + 0.0000000000000000001... bye |