Encoders
Hub for Computer Whizzes Register to join us

Encoders > More... > C > Program

/* Function atof(s) extended to handle scientific notation of the form
   123.45e-6 where a floating-point number may be followed by e or E and an
   optionally signed exponent. */

#include <stdio.h>

double atof(char s[]);

main()
{
	char a[100];
	double i;
	gets(a);
        printf("%f\n",atof(a));
}

double atof(char s[])
{
	double pow(double base, int n);
	double n, power;
	int i, sign[2]={1,1},exp=0;
	for(i=0; s[i]==' ' || s[i]=='\t' || s[i]=='\n'; i++)
		;
	if(s[i]=='-' || s[i]=='+')
		sign[0] = s[i++]=='-'?-1:1;
        for(n=0; s[i]>='0'&&s[i]<='9'; i++)
		n = n*10 + s[i]-'0';

	if(s[i]=='.')
		i++;
        for(power=1;s[i]>='0'&&s[i]<='9';i++)
	{
		n=n*10 + s[i]-'0';
		power *= 10;
	}
	if(s[i]=='e'||s[i]=='E')
		i++;
        if(s[i]=='-' || s[i]=='+')
		sign[1] = s[i++]=='-'?-1:1;
        for(exp=0; s[i]>='0'&&s[i]<='9'; i++)
		exp = exp*10 + s[i]-'0';
	return (sign[0]*n/power)*pow(10,sign[1]*exp);
}

double pow(double base, int n)
{
	double p;
        if(n<0)
		base = 1/base, n = -n;
        for(p=1;n>0;n--)
		p*=base;
	return p;
}