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

How to check whether string is a palindrome, WITHOUT USING STRING FUNCTIONS?

15517


What do you understand by friend-functions? How are they used?

653


What are type modifiers in c?

625


1.int a=10; 2.int b=20; 3. //write here 4.b=30; Write code at line 3 so that when the value of b is changed variable a should automatically change with same value as b. 5.

1670


which of the following is not a character constant a) 'thank you' b) 'enter values of p, n ,r' c) '23.56E-o3' d) all of the above

1421






What is the basic structure of c?

563


c language supports bitwise operations, why a) 'c' language is system oriented b) 'c' language is problem oriented c) 'c' language is middle level language d) all the above

619


a c code by using memory allocation for add ,multiply of sprase matrixes

2306


Is python a c language?

555


What is getch?

636


printf(), scanf() these are a) library functions b) userdefined functions c) system functions d) they are not functions

640


Find MAXIMUM of three distinct integers using a single C statement

630


Can a program have two main functions?

575


Describe explain how arrays can be passed to a user defined function

609


Is it acceptable to declare/define a variable in a c header?

688