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 double pointer in c?
Is main an identifier in c?
What is the best way of making my program efficient?
How pointer is different from array?
Why c is a procedural language?
How do you generate random numbers in C?
Can you write the function prototype, definition and mention the other requirements.
What are the applications of c language?
Why do we use header files in c?
What are terms in math?
Write a code to generate a series where the next element is the sum of last k terms.
What is calloc malloc realloc in c?
What does %c mean in c?
You are to write your own versions of strcpy() and strlen (). Call them mystrcpy() and mystrlen(). Write them first as code within main(), not as functions, then, convert them to functions. You will pass two arrays to the function in the case of mystrcpy(), the source and target array.
What is dynamic memory allocation?