Hatena::Groupcprogramming

てーげーC言語

2009-03-04

4-2

| 00:44

#include <stdio.h>
#include <ctype.h>

double atof (char s[]) {
  double val, power, sisu;
  int i, sign, sisuketa;

  for (i = 0; isspace(s[i]); i++)
    ;   

  sign = (s[i] == '-') ? -1 : 1;

  if (s[i] == '+' || s[i] == '-')
    i++;

  for (val = 0.0; isdigit(s[i]); i++)
    val = 10.0 * val + (s[i] - '0');

  if (s[i] == '.')
    i++;

  for(power = 1.0; isdigit(s[i]); i++) {
    val = 10.0 * val +(s[i] - '0');
    power *= 10.0;
  }

  sisu = 1.0;

  if(((s[i] == 'e') || (s[i] == 'E')) && (s[++i] == '-')){
    i++;
    for(sisuketa = 0; isdigit(s[i]); i++) {
      sisuketa = 10 * sisuketa + (s[i] - '0');
    }   

    for(sisu = 1.0; sisuketa > 0; sisuketa--) {
      sisu *= 10.0;
    }   
  }

  return sign * val / power / sisu;
}

int main() {
  char s[] = "10.5";
  char t[] = "3.42e-4";

  printf("%f\n", atof(s));
  printf("%f\n", atof(t));
  return 0;
}
# ./a.out                
10.500000
0.000342