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
What are the disadvantages of external storage class?
explain how do you use macro?
What are the usage of pointer in c?
What is extern variable in c with example?
How to write c functions that modify head pointer of a linked list?
Does c have an equivalent to pascals with statement?
exit () is used to a) exit () terminates the execution of the program itself b) exit () terminates the execution of the loop c) exit () terminates the execution of the block d) none of the above
The number of bytes of storage occupied by short, int and long are a) 2, 2 and 4 b) 2, 4 and 4 c) 4, 4 and 4 d) none
What is 2c dna?
What is a loop?
Which is the best website to learn c programming?
What's the right way to use errno?
Hi can anyone tell what is a start up code?
what are the advanced features of functions a) function declaration and prototypes b) calling functions by value or by reference c) recursion d) all the above
What is array of pointers to string?