Write a C program Write a function that receives a string an

Write a C program

Write a function that receives a string and return a double floating-point value. The function declaration would look like this

double convertFloat(char s[]);

Do not use strtol() function or any other standard C library function. Write your own! Include a test program for the function. Note that the input string could have any of the following sample formats: \"5.32\", \"-1.6434\", \"8\".

Your function should be in a program with tests for several floating point numbers.

Solution

Code:

#include <stdio.h>
#include <string.h>


int power(int n, int m)
{
if (m == 1)
return n;
else
return n * (power(n, m - 1));
}

int getLength(char s[])
{
int i = 0;
for(i = 0; s[i] != \'\\0\'; i++);
return i;
}


double convertFloat(char s[])
{
int len = getLength(s);
int dotpos = 0;
double result = 0.0f;
int n = 0, flag = 0;
if(s[0] == \'-\')
{
n = 1;
flag = 1;
}
for (; n < len; n++)
{
if (s[n] == \'.\')
{
dotpos = len - n - 1;
}
else
{
result = result * 10 + (s[n] - \'0\');
}
}
result /= power(10, dotpos);
if(flag)
return result*-1;
return result;
}

int main ( ) {
printf(\"%f\",convertFloat(\"5.32\"));

return 0;
}

Write a C program Write a function that receives a string and return a double floating-point value. The function declaration would look like this double convert
Write a C program Write a function that receives a string and return a double floating-point value. The function declaration would look like this double convert

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site