Write code to implement atof (string to float)
Code:double atof(char *s) { double a = 0.0; int e = 0; int c; while ((c = *s++) != '\0' && isdigit(c)) { a = a*10.0 + (c - '0'); } if (c == '.') { while ((c = *s++) != '\0' && isdigit(c)) { a = a*10.0 + (c - '0'); e = e-1; } } if (c == 'e' || c == 'E') { int sign = 1; int i = 0; c = *s++; if (c == '+') c = *s++; else if (c == '-') { c = *s++; sign = -1; } while (isdigit(c)) { i = i*10 + (c - '0'); c = *s++; } e += i*sign; } while (e > 0) { a *= 10.0; e--; } while (e < 0) { a *= 0.1; e++; } return a; }
#include<iostream>
using namespace std;
double atof( char *s)
{
int sign=1
if(s == NULL)
return 0;
if( *s == '-')
sign=-1;
double out=0;
while( s !=NULL || *s !='\0')
{
if(*s == ' ')
continue;
if(*s == '.')
break;
if( *s > '9' || *s < '0')
return 0;
out= out*10+(*s - '0');
s++;
}
double decimalOut=0;
int decCount=0;
while( s != NULL && *s == '.')
{
if(*s == ' ')
continue;
if(*s == '\0')
break;
if( *s > '9' || *s < '0')
return 0;
decimal= decimal*10+(*s - '0');
decimalCount++;
}
return sign*(out + (0.1 ^ decimalCount)*decimalcount);
}
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks