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


Please Help Members By Posting Answers For Below Questions

What is double pointer in c?

593


Is main an identifier in c?

607


What is the best way of making my program efficient?

573


How pointer is different from array?

586


Why c is a procedural language?

587






How do you generate random numbers in C?

664


Can you write the function prototype, definition and mention the other requirements.

666


What are the applications of c language?

630


Why do we use header files in c?

588


What are terms in math?

598


Write a code to generate a series where the next element is the sum of last k terms.

742


What is calloc malloc realloc in c?

598


What does %c mean in c?

656


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.

1785


What is dynamic memory allocation?

812