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
Is multithreading possible in c?
Write a code to achieve inter processor communication (mutual exclusion implementation pseudo code)?
Are the outer parentheses in return statements really optional?
If null and 0 are equivalent as null pointer constants, which should I use?
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
Why main is not a keyword in c?
What is a lookup table in c?
What is the difference between #include
How #define works?
Explain the use of 'auto' keyword
Explain how do you sort filenames in a directory?
How can I call fortran?
Tell me can the size of an array be declared at runtime?
Can you please explain the difference between exit() and _exit() function?
What is gets() function?