Friday, 20 September 2013

Improvement to Adam's code

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int flag = 0;

double validate(char* x)
{
  int numOfDec = 0;
  int i = 0;

  if(x[i] == '-')
  {
    i++;
  }
/*   using lazy evaluation, this block of code can be shortened to 4 lines below
  while(x[i] != '\0')
  {
    if(!(isdigit(x[i])))
    {
      if(x[i] == '.')
      {
        numOfDec++;
        if((numOfDec) > 1)
        {
          flag = 1;
        }
      }
      else flag = 1;
    }
    i++;
  } */

while(x[i] != '\0'){

   (x[i] == '.') && (numOfDec+=1);

   ((numOfDec > 1) || (!(isdigit(x[i])))) && (flag = 1);

   i++;
}
  if(!flag)
    return atof(x);
  else
    return 0;
}

int main(int argc, char** argv)
{

  double newNum;
  // int numberOfDecimalPoingt = 0;       this variable is stated, but never used

  if(argc != 4)
  {
    flag = 1;
  }
  else
  {
    /*if(strlen(argv[2]) != 1)    this statement is taken out because it's not needed after modifying the validation underneath
    {
      flag = 1;
    }
    else */
      if(strcmp(argv[2],  "+")==0) newNum = validate(argv[1]) + validate(argv[3]);
      else if(strcmp(argv[2],  "-")==0) newNum = validate(argv[1]) - validate(argv[3]);
      else if(strcmp(argv[2],  "x")==0) newNum = validate(argv[1]) * validate(argv[3]);
      else if(strcmp(argv[2],  "/")==0) newNum = validate(argv[1]) / validate(argv[3]);
      else flag = 1;
  }

  if(flag)
  {
    printf("Format must be <number> <+-x/> <number>\n");
  }
  else
  {
    printf("%g\n", newNum);
  }

  return 0;
}

No comments:

Post a comment