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

Why C language is a procedural language?

614


What is nested structure with example?

616


Difference between MAC vs. IP Addressing

632


Difference between goto, long jmp() and setjmp()?

697


What is ## preprocessor operator in c?

607






What is a stream in c programming?

587


What do you mean by keywords in c?

616


Explain what are reserved words?

630


On most computers additional memory that is accessed through an adapter of feature card along with a device driver program. a) user memory b) conventional memory c) expandedmemory d) area

652


what is a NULL Pointer? Whether it is same as an uninitialized pointer?

753


Why we write conio h in c?

552


Write a client and server program in C language using UDP, where client program interact with the Server as given below: i) The client begins by sending a request to send a string of 8 characters or series of 7 numbers, the server sends back a characters or numbers as per the request of the client. ii) In case of series of 7 numbers: The client sends a multiplication of numbers, to the server. iii) In case of a string of 8 characters: The client sends a reverse order of string to the server.. iv) Server will send an acknowledgment to the client after receiving the correct answer

3832


In C programming, what command or code can be used to determine if a number of odd or even?

618


How can I convert a number to a string?

602


Explain what is the general form of a c program?

616