C Program, Document everyline please Write a function that receives a string and
ID: 3794481 • Letter: C
Question
C Program, Document everyline please
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 the 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: "1.34", "-1.4554", "6". Optional: If you are interested, you can also extend your function to handles strings that contains number in scientific notation, e.g., "4.1e-5". Your function should be in a program with tests for several floating-point numbers.Explanation / Answer
// C code
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <assert.h>
#include <string.h>
#include <ctype.h>
#include <inttypes.h>
#include <stdbool.h>
#include <unistd.h>
double convertFloat(char floatString[])
{
double floatingPointValue = 0;
double factValue = 1;
// get the '-' character for scientific notations
if (*floatString == '-')
{
floatString++;
factValue = -1;
};
// iterate over string
for (int j = 0; *floatString; floatString++)
{
// check for decimal
if (*floatString == '.')
{
j = 1;
continue;
};
int doubleValue = *floatString - '0';
if (doubleValue >= 0 && doubleValue <= 9)
{
if (j) factValue /= 10.0f;
// add the converstion to the result floating point value
floatingPointValue = floatingPointValue * 10.0f + (double)doubleValue;
};
};
return floatingPointValue * factValue;
};
int main()
{
char s[100];
printf("Enter floating point string: : ");
scanf("%s",s);
printf("Floating point value: %lf ",convertFloat(s));
return 0;
}
/*
output;
Enter floating point string: : -1.4554
Floating point value: -1.455400
Enter floating point string: : 1.34
Floating point value: 1.340000
Enter floating point string: : 4.1e-5
Floating point value: 4.150000
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.