Write an implementation of “float stringToFloat(char *str).”
The code should be simple, and not require more than the
basic operators (if, for, math operators, etc.).
• Assumptions
• Don’t worry about overflow or underflow
• Stop at the 1st invalid character and return the number
you have converted till then, if the 1st character is
invalid return 0
• Don’t worry about exponential (e.g. 1e10), instead you
should treat ‘e’ as an invalid character
• Write it like real code, e.g. do error checking
• Go though the string only once
• Examples
• “1.23” should return 1.23
• “1a” should return 1
• “a”should return 0

Answer Posted / c l

float stringToFloat(char *str)
{
float retVal = 0;
float devisor = 1;
int strSize = sizeof(str);
int multiplySign = 1;
bool foundDecimal = false;

/* check for non empty char array */
if (strSize > 0 )
{
if (str[0] >= '0' && str[0] <= '9')
retVal = str[0] - '0';

else if (str[0] == '.')
foundDecimal = true;

else if (str[0] == '-')
mulitplySign = -1;

else if (str[0] == '+')
; /* NOP */

else
return retVal;

for (i = 1; i < strSize; i++)
{
if (str[i] >= '0' && str[i] <= '9')
{
retValue = retValue*10 + str[i] - '0';
if (foundDecimal)
divisor = divisor * 10;
}
else if (str[i] == '.')
if(foundDecimal) /* 2nd '.', err */
break;
else
foundDecimal = true;

else /* anything else is err cond */
break;
}

return multiplySign * retVal / divisor;
}
}

Is This Answer Correct ?    0 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Differentiate between ordinary variable and pointer in c.

613


Explain what are reserved words?

630


What is new line escape sequence?

803


Where is c used?

644


can any one provide me the notes of data structure for ignou cs-62 paper

1694






Differentiate between declaring a variable and defining a variable?

602


How can you invoke another program from within a C program?

609


`write a program to display the recomended action depends on a color of trafic light using nested if statments

1629


What is the general form of function in c?

607


What is the use of extern in c?

639


Write a program to print ASCII code for a given digit.

679


When the macros gets expanded?

780


How many types of operator or there in c?

595


to find the closest pair

1816


What are the advantages and disadvantages of c language?

554