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 / nikita
#include<stdio.h>
#include<string.h>
int main()
{
int i = 0;
float result = 0;
int dec_count = 0;
int isDec = 0;
char* str = "123.76bg";
while(str[i])
{
if(str[i] == '.')
{
isDec = 1;
i++;
}
if((str[i]>=48) && (str[i]<=57))
{
result = result * 10;
result = result + (str[i++] - '0');
}
else
{
break;
}
if(isDec == 1)
{
dec_count++;
}
}
printf("\nThe result is: %f", result);
for(i=0; i<dec_count; i++)
{
result = result / 10;
}
printf("\nThe result is: %f", result);
return 0;
}
| Is This Answer Correct ? | 1 Yes | 2 No |
Post New Answer View All Answers
What is main () in c language?
What kind of structure is a house?
What is spaghetti programming?
For what purpose null pointer used?
What is scope rule in c?
Is main is a keyword in c?
Write a program to print "hello world" without using a semicolon?
What is function what are the types of function?
What is LINKED LIST? How can you access the last element in a linked list?
What is the role of && operator in a program code?
Once I have used freopen, how can I get the original stdout (or stdin) back?
What will the code below print when it is executed? int x = 3, y = 4; if (x = 4) y = 5; else y = 2; printf ("x=%d, y=%d ",x,y);
if a is an integer variable, a=5/2; will return a value a) 2.5 b) 3 c) 2 d) 0
What is a macro?
how much salary u want ? why u join in our company? your domain is core sector why u prefer software ?