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 is external variable in c?
What is pointers in c with example?
all c language question
Differentiate between declaring a variable and defining a variable?
Which one to choose from 'initialization lists' or 'assignment', for the use in the constructor?
What are the functions to open and close the file in c language?
What is the purpose of realloc()?
i have to apply for rbi before that i need to know the the syllabus for the entrance questions. whethet it may be aps or techinical
Function calling procedures? and their differences? Why should one go for Call by Reference?
Explain what is the heap?
What is c programing language?
How is actual parameter different from the formal parameter?
What is an lvalue?
write a c program for swapping two strings using pointer
Read the following data in two different files File A: aaaaaaaadddddddd bbbbbbbbeeeeeeee ccccccccffffffff File B: 11111111 22222222 33333333 By using the above files print the following output or write it in the Other file as follows aaaaaaaa11111111dddddddd bbbbbbbb22222222eeeeeeee cccccccc33333333ffffffffffff