Created
November 3, 2016 13:15
-
-
Save Highstaker/9e4a0269ced96f4e1cb3a70c5382904b to your computer and use it in GitHub Desktop.
A function that transforms strings into a double. Supports E notation.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <ctype.h> | |
#include <stdio.h> | |
#include <math.h> | |
double atod(char * s) | |
{ | |
int i; | |
for(i=0;isspace(s[i]);i++); | |
int sign = 1; | |
for(;s[i] == '-' || s[i] == '+';i++) | |
{ | |
if(s[i] == '-') | |
{ | |
sign = -sign; | |
} | |
} | |
double result = 0.0; | |
for(;isdigit(s[i]);i++) | |
{ | |
result = 10.0 * result + (s[i] - '0'); | |
} | |
int pow10=0; | |
if(s[i] == '.') | |
{ | |
i++; | |
for(;isdigit(s[i]);i++) | |
{ | |
result = 10.0 * result + (s[i] - '0'); | |
pow10--; | |
} | |
} | |
int exp_sign = 1; | |
int ex = 0; | |
if(s[i] == 'e' || s[i] == 'E') | |
{ | |
i++; | |
for(;s[i] == '-' || s[i] == '+';i++) | |
{ | |
if(s[i] == '-') | |
{ | |
exp_sign = -exp_sign; | |
} | |
} | |
for(;isdigit(s[i]);i++) | |
{ | |
ex = 10.0 * ex + (s[i] - '0'); | |
} | |
int j; | |
if(exp_sign > 0) | |
{ | |
for(j=0;j<ex;j++) | |
{ | |
pow10++; | |
} | |
} | |
else | |
{ | |
for(j=0;j<ex;j++) | |
{ | |
pow10--; | |
} | |
} | |
} | |
double divisor = 1.0; | |
for(i=0;i<abs(pow10);i++) | |
{ | |
divisor *= 10.0; | |
} | |
printf("pow10: %d\n", pow10);//debug | |
printf("exp_sign: %d\n", exp_sign);//debug | |
printf("divisor: %f\n", divisor);//debug | |
if(pow10 > 0) | |
{ | |
result = result * divisor; | |
} | |
else | |
{ | |
result = result / divisor; | |
} | |
return result; | |
}//atod | |
int main(int argc, char const *argv[]) | |
{ | |
printf("%f\n", atod((char *)argv[1])); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment