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
What are header files? What are their uses?
What is data type long in c?
Write a program to check whether a number is prime or not using c?
What is the maximum length of an identifier?
Where does the name "C" come from, anyway?
What type of function is main ()?
What is c value paradox explain?
Tell us bitwise shift operators?
What is I ++ in c programming?
What is the difference between class and object in c?
Disadvantages of C language.
What does 3 periods mean in texting?
What is wrong with this code?
How to get string length of given string in c?
Is array a primitive data type in c?