Amazon Interview Question
Software Engineer / DevelopersTeam: Kindle
Country: India
Interview Type: In-Person
// this shud work :
void ftoa(float num, char *str)
{
int intpart = num;
int intdecimal;
int i;
float decimal_part;
char decimal[20];
memset(str, 0x0, 20);
itoa(num, str, 10);
strcat(str, ".");
decimal_part = num - intpart;
intdecimal = decimal_part * 1000000;
if(intdecimal < 0)
{
intdecimal = -intdecimal;
}
itoa(intdecimal, decimal, 10);
for(i =0;i < (PRECISION - strlen(decimal));i++)
{
strcat(str, "0");
}
strcat(str, decimal);
}
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....
Pls comment on this code.
#define PRECESION 10000000
int _tmain(int argc, _TCHAR* argv[])
{
float input = -12340.004321;
char itamap[10] = {'0','1','2','3','4','5','6','7','8','9'};
char val[20] = {0};
float tempdecimal, value;
int intpart;
int index = 0;
value = input;
if(value < 0) // handle -ve
{
val[index++] = '-';
value *= -1;
}
else
val[index++] = '+';
intpart = value;
tempdecimal = value - intpart;
if(intpart == 0)
{
val[index++] = itamap[intpart];
}
while(intpart)
{
val[index++] = itamap[ intpart%10];
intpart /= 10;
}
val[index] = '.';
int i = 1 , j = index-1;
for(i; i <index/2; i++,j--)
{
char temp = val[i];
val[i] = val[j];
val[j] = temp;
}
index++;
int decimalIndex = 10;
i = 10;
while(decimalIndex*i < PRECESION)
{
tempdecimal *= decimalIndex;
intpart = tempdecimal;
tempdecimal -= intpart;
val[index++] = itamap[intpart];
i *= 10;
}
printf("%s",val);
return 0;
}
#include<stdio.h>
void ftoa(float a,char s[])
{ float b=a;
int c;
if(b<0)
{
a=-a;
}
i=0;
c=(int)a;
float d1=a-c;
if(d1>0)
{
int count=0;
while(d1<1)
{
d1*10;count++;
}
}
do{
s[i++]=n%10+'0';}
s[i++]='.'
int n=(int )d1;
do{
s[i++]=n%10+'0';}
s[i++]='.'
while((n/=10)>0);
int n=c;
do{
s[i++]=n%10+'0';}
s[i++]='.'
while((n/=10)>0);
if(b<0)
s[i++]='-';
s[i]='\0'
reverse(s);
}
float num = 24.3;
- Anonymous July 15, 2012char ch[MAX_SIZE];
sprintf(ch,"%f",num);