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
Differentiate between ordinary variable and pointer in c.
Explain what are reserved words?
What is new line escape sequence?
Where is c used?
can any one provide me the notes of data structure for ignou cs-62 paper
Differentiate between declaring a variable and defining a variable?
How can you invoke another program from within a C program?
`write a program to display the recomended action depends on a color of trafic light using nested if statments
What is the general form of function in c?
What is the use of extern in c?
Write a program to print ASCII code for a given digit.
When the macros gets expanded?
How many types of operator or there in c?
to find the closest pair
What are the advantages and disadvantages of c language?