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
Why C language is a procedural language?
What is nested structure with example?
Difference between MAC vs. IP Addressing
Difference between goto, long jmp() and setjmp()?
What is ## preprocessor operator in c?
What is a stream in c programming?
What do you mean by keywords in c?
Explain what are reserved words?
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
what is a NULL Pointer? Whether it is same as an uninitialized pointer?
Why we write conio h in c?
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
In C programming, what command or code can be used to determine if a number of odd or even?
How can I convert a number to a string?
Explain what is the general form of a c program?