Ok, I coded a simple representation of an extended Atof:
Code:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <math.h>
#ifndef MAXSIZE
#define MAXSIZE 1000
#endif
enum bool {TRUE = 1, FALSE = 0};
long double Atof(char* s)
{
enum bool isNegative = FALSE;
long double val, power;
int i, sign, exp;
/* while it's a space, keep iterating */
for(i = 0; isspace(s[i]); i++)
;
/* record the sign */
sign = (s[i] == '-')? -1 : 1;
/* if it is a sign, just ignore it iterating to the next index */
if(s[i] == '-' || s[i] == '+')
i++;
/* get the power and the value for further manipulation */
/* ----------------------------------------------------- */
for(val = 0.0; isdigit(s[i]); i++)
val = 10 * val + (s[i] - '0');
if(s[i] == '.')
i++;
for(power = 1.0; isdigit(s[i]); i++)
{
val = 10 * val + (s[i] - '0');
power *= 10;
}
/* ----------------------------------------------------- */
/* just ignore if 'e' or 'E' was entered */
if(s[i] == 'e' || s[i] == 'E')
{
i++;
/* test if the exponent is negative */
if(s[i] == '-')
isNegative = TRUE;
i++;
/* test if the next char is a digit */
if(isdigit(s[i]))
exp = s[i] - '0';
/* if the exponent is negative, make the exp value negative
* and return the proper value */
if(isNegative)
{
exp = -exp;
return (sign * val / power) * pow(10.0, exp);
}
/* the exponent isn't negative, so don't make the exp value negative */
else {
return (sign * val / power) * pow(10.0, exp);
}
}
/* 'e' or 'E' wasn't entered, just return the value with the adequate sign */
else {
return val * sign / power;
}
}
int main(void)
{
char strnum[MAXSIZE];
long double d;
printf("Please enter a number in scientific notation of the form ");
printf("[number]e-[exponent] or [number]E-[exponent]: ");
fgets(strnum, sizeof(strnum), stdin);
d = Atof(strnum);
printf("The double value in scientific notation is %Lf\n", d);
return 0;
}
I don't understand why even declaring my vars as long double, I can't get the precision offered by this type.