Amazon Interview Question
Developer Program Engineersthis is a good way , to use sprintf,
here is another way, without sprintf:
I haven't consider negative number , only decimal float are considerred .
void myftoa(float x)
{
int i=x;
int j;
float m=x-(float)i;
char CInt[18]={0}; // biggest integer decimal would be 10 digital, we need another 1 for'.', 1 for 0
for( j=0;j<10;j++)
{
if(i/10!=0)
{
CInt[10-j-1]=i%10+'0';
i=i/10;
}
else
{
if(i%10!=0)
{
CInt[10-j-1]=i%10+'0';
}
break;
}
}
char *result=&(CInt[10-j-1]);
char Cmas[7]={0}; // only have to handle value bigger than 0.000001
for(int i=0;i<6;i++)
{
Cmas[i]=(int)(m*10)+'0';
m=m*10-(int)(m*10);
}
char *p=".";
result=strcat(result,p);
result=strcat(result,Cmas);
printf("%s", result);
}
Use sprintf
or check this for implementing ftoa without using sprintf:
char* floatToString(float num)
{
int whole_part = num;
int digit = 0, reminder =0;
int log_value = log10(num), index = log_value;
long wt =0;
// String containg result
char* str = new char[20];
//Initilise stirng to zero
memset(str, 0 ,20);
//Extract the whole part from float num
for(int i = 1 ; i < log_value + 2 ; i++)
{
wt = pow(10.0,i);
reminder = whole_part % wt;
digit = (reminder - digit) / (wt/10);
//Store digit in string
str[index--] = digit + 48; // ASCII value of digit = digit + 48
if (index == -1)
break;
}
index = log_value + 1;
str[index] = '.';
float fraction_part = num - whole_part;
float tmp1 = fraction_part, tmp =0;
//Extract the fraction part from num
for( int i= 1; i < PRECISION; i++)
{
wt =10;
tmp = tmp1 * wt;
digit = tmp;
//Store digit in string
str[++index] = digit +48; // ASCII value of digit = digit + 48
tmp1 = tmp - digit;
}
return str;
}
float f;
int k,count=0,i=0;
char s[20];
scanf("%f",&f);
k=(int)f;
while(f-k!=0.0)
{
f=f*10;
k1=(int)f;
count++;
}
//now f is in integer format and now decimal can be placed using count
while(f>0)
{
if(count!=0)
{
s[i]=(f%10)+48;
f=f/10;
}
else
{
s[i]='.';
}
i++;
count--;
}
//reversing the above string gives the desired result....
awaiting u r responses :)
Use sprintf function.
- AmitG November 17, 2010sprintf(buffer, "%f", f);
will print value of f into string buffer.