Skip to content

Instantly share code, notes, and snippets.

@bojieli
Created November 12, 2014 14:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bojieli/4afa2b7beb23993a31ab to your computer and use it in GitHub Desktop.
Save bojieli/4afa2b7beb23993a31ab to your computer and use it in GitHub Desktop.
String to double conversion
#include<stdio.h>
int main() {
double sign = 1, intpart = 0, decmod = 1;
int expsign = 1, exp = 0;
double ans;
int i;
char c;
c = getchar();
if (c == '-') {
sign = -1;
c = getchar();
}
if (c == '+') {
sign = 1;
c = getchar();
}
while (c >= '0' && c <= '9') {
intpart = intpart * 10 + c - '0';
c = getchar();
}
if (c == '.') {
c = getchar();
while (c >= '0' && c <= '9') {
intpart = intpart * 10 + c - '0';
decmod *= 10;
c = getchar();
}
}
if (c == 'e' || c == 'E') {
c = getchar();
if (c == '+') {
expsign = 1;
c = getchar();
}
if (c == '-') {
expsign = -1;
c = getchar();
}
while (c >= '0' && c <= '9') {
exp = exp * 10 + c - '0';
c = getchar();
}
}
ans = sign * intpart / decmod;
if (expsign == 1) {
for (i=0; i<exp; i++)
ans *= 10;
} else {
for (i=0; i<exp; i++)
ans /= 10;
}
printf("%lf\n", ans);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment