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 / piyush sharma

float stringToFloat(char *str)
{
char ch;
int decimal_pt = 0;
int dec_count = 0;
float val = 0.0;

for( int i=0; str[i]!='\0'; i++ )
{
ch = str[i];
if( ch == '.' )
{
decimal_pt = 1;
continue;
}

if( !(ch>=48 && ch<=57) )
break;

val = val*10 + ch-48;
if( decimal_pt == 1 )
dec_count++;
}

for( int i=0; i<dec_count; i++ )
val = val/10;

return val;
}

Is This Answer Correct ?    2 Yes 2 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Is multithreading possible in c?

568


Write a code to achieve inter processor communication (mutual exclusion implementation pseudo code)?

689


Are the outer parentheses in return statements really optional?

577


If null and 0 are equivalent as null pointer constants, which should I use?

577


What does a derived class inherit from a base class a) Only the Public members of the base class b) Only the Protected members of the base class c) Both the Public and the Protected members of the base class d) .c file

668






Why main is not a keyword in c?

650


What is a lookup table in c?

627


What is the difference between #include

and #include “header file”?

552


How #define works?

617


Explain the use of 'auto' keyword

679


Explain how do you sort filenames in a directory?

608


How can I call fortran?

643


Tell me can the size of an array be declared at runtime?

599


Can you please explain the difference between exit() and _exit() function?

594


What is gets() function?

673