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
#include<iostream>
using namespace std;
int main()
{
char* str = "36.78sg67";
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;
cout << val << endl;
system("pause");
return 0;
}
| Is This Answer Correct ? | 3 Yes | 1 No |
Post New Answer View All Answers
Explain pointers in c programming?
Which are low level languages?
what is the height of tree if leaf node is at level 3. please explain
What are the advantages of c language?
What is a program flowchart and how does it help in writing a program?
What do you mean by keywords in c?
How can I call a function with an argument list built up at run time?
What is variable and explain rules to declare variable in c?
What is the return type of sizeof?
What is a header file?
Can a function be forced to be inline? Also, give a comparison between inline function and the C macro?
Is array name a pointer?
Hai sir, I had planned to write the NIC scientific engineer exam , plz post the sample question......
What is the difference between malloc calloc and realloc in c?
What does the file stdio.h contain?