atof

So given a string like "2.23" your function should return double 2.23. This might seem easy in the first place but this is a highly ambiguous question. Also it has some interesting test cases. So overall a good discussion can revolve around this question. We are not going to support here scientific notation like 1.45e10 etc. We will also not support hex and octal strings just for the sake of simplicity. But these are good assumption to state upfront. Let's write code for this.
double atof(char* num)
{
if (!num || !*num)
return ;
double integerPart = ;
double fractionPart = ;
int divisorForFraction = ;
int sign = ;
bool inFraction = false;
/*Take care of +/- sign*/
if (*num == '-')
{
++num;
sign = -;
}
else if (*num == '+')
{
++num;
}
while (*num != '\0')
{
if (*num >= '' && *num <= '')
{
if (inFraction)
{
/*See how are we converting a character to integer*/
fractionPart = fractionPart* + (*num - '');
divisorForFraction *= ;
}
else
{
integerPart = integerPart* + (*num - '');
}
}
else if (*num == '.')
{
if (inFraction)
return sign * (integerPart + fractionPart/divisorForFraction);
else
inFraction = true;
}
else
{
return sign * (integerPart + fractionPart/divisorForFraction);
}
++num;
}
return sign * (integerPart + fractionPart/divisorForFraction);
}
上一篇:[ES6] Array.findIndex()


下一篇:设置Hyper-V和VMware多个服务之间共存