i know this has been mentioned over and over (and over) again in this forum but i would like to ask specifically on a function i've been playing around:
obviously that i want to convert float -> string.Code:#include <stdio.h> #include <stdlib.h> char *ftoi(float f){ char str[20]; char *fstr; float a; fstr= malloc(100); sprintf(str,"%i",(int)f); // get the int part and make it string strcat(fstr,str); // store this part inside the main string strcat(fstr,"."); // oh, put the decimal place too f-=(int)f; // keep the part after the decimal place while(f>0){ printf("%f\n",f); f*=10; // move the number 1 decimal place left printf("%f\n\n",f); sprintf(str,"%i",(int)f); // make int part -> string strcat(fstr,str); // store it f-=(int)f; // keep only decimal } printf("%s\n",fstr); return fstr; }
but then all hell breaks loose. say for f=2,55 my printf's are the following:
most probably the problem is at the multiplication. i even tried fdimf()Code:0.550000 //ok let's see 5.500000 //so far so good 0.500000 //...ok... 4.999995 // nooooooooooo.... 0.999995 //&^*&^%&^&*ing ^$%#^% 9.999952 0.999952 9.999523 0.999523 9.995232 0.995232 9.952316 0.952316 9.523163 0.523163 5.231628 0.231628 2.316284 0.316284 3.162842 0.162842 1.628418 0.628418 6.284180 0.284180 2.841797 0.841797 8.417969 0.417969 4.179688 0.179688 1.796875 0.796875 7.968750 0.968750 9.687500 0.687500 6.875000 0.875000 8.750000 0.750000 7.500000 0.500000 5.000000 // now that's funny, no 4.99 i guess it didn't have any other blocks to read 2.5499999523162841796875 // :-/
because of the so called "infinite precision" but i saw no change at all...Code:fdimf(f,10,0) or fdimf(f, 10.0, 0)
played with doubles a bit too but nothing again...
any suggestions on what should i do (except from messing with floats unless i'm using matlab) ?
thank's in advance guys.



LinkBack URL
About LinkBacks



