[ create a new paste ] login | about

Link: http://codepad.org/NBYcgHii    [ raw code | output | fork ]

C, pasted on Jul 18:
#include <stdio.h>

void
pp(double n[], char op[])
{
  return;
  printf("%f %c %f %c %f\n", n[0], op[0], n[1], op[1], n[2]);
}

double
calc(char s[])
{
  char           *p1 = s, s2[100], *p2 = s2, op[2];
  double          n[3];
  int             i;
  //文字列を数字と演算子に分解
  while (*p1) {
    if ((*p1 >= '0') && (*p1 <= '9')) {
      *p2++ = *p1++;
    } else {
      *p2++ = ' ';
      *p2++ = *p1++;
      *p2++ = ' ';
    }
  }
  *p2 = '\0';
  sscanf(s2, "%lf %c %lf %c %lf", n, op, n + 1, op + 1, n + 2);
  pp(n, op);

  //式を変形(例:5 / 2 - 4--->2.5 * 1 + -4)
  for (i = 0; i < 2; i++) {
    if (op[i] == '*') {
      n[i] *= n[i + 1];
      n[i + 1] = 1;
    }
    if (op[i] == '/') {
      n[i] /= n[i + 1];
      n[i + 1] = 1;
      op[i] = '*';
    }
    if (op[i] == '-') {
      n[i + 1] *= -1;
      op[i] = '+';
    }
  }
  pp(n, op);
  for (i = 0; i < 2; i++) {
    if (op[i] == '*') {
      n[i + 1] *= n[i];
    } else {
      n[i + 1] += n[i];
    }
  }
  pp(n, op);
  return n[2];
}

int
main()
{
  char            s[100];
  printf("input end = Ctrl + d\n");
  while (printf("input:"), 1 == scanf("%s", s)) {
    printf("answer = %f\n", calc(s));
  }
  return 0;
}


Output:
1
2
input end = Ctrl + d
input:


Create a new paste based on this one


Comments: