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

[K&R}4-1

| 00:41

#include <stdio.h>
#include <string.h>

void reverse(char* s)
{
  int i, j;
  char temp, *p;

  i = j = 0;
  p = s;


  while(*p++) {
    i++;
  }

  --i;
  while(i > j) {
    temp = *(s+i);
    *(s+i) = *(s+j);
    *(s+j) = temp;
    i--;
    j++;
  }
}

int strrindex(char* s, char* t) {
  int len, i, j;

  len = strlen(s);
  i = len;

  reverse(t);

  while(i-- >= 0) {
    for(j = 0; (*(s+i) == *(t+j)) &&  (*(t+j) != '\0'); i--, j++) {
    }   

    if (*(t+j) == '\0')
      return i+1;
  }
  return -1; 
}

int main()
{
  char* s = "helloworld";
  char t[] = "world";
  char* u = "hogebarfuga";
  char v[] = "bar";
  char* w = "rubyperlphp";
  char x[] = "java";
  char* y = "helloworldhelloworld";
  char z[] = "hello";
  int rtn;

  rtn = strrindex(s, t);
  printf("%d\n", rtn);

  rtn = strrindex(u, v);
  printf("%d\n", rtn);

  rtn = strrindex(w, x);
  printf("%d\n", rtn);

  rtn = strrindex(y, z);
  printf("%d\n", rtn);

  return 0;
}
# ./a.out                
5
4
-1
10