Friday, 20 September 2013

Simple Math problem OOP344

 /*The way I chose to do it is to use atof() after the parameters have passed each check, this way if there are any logic errors it would be easy to debug at each check point */

#include <cstring>
#include <cstdlib>
#include <stdio.h>

int main(int argc, char** argv){
   if(!(argc==4)){      //check number of parameters
      printf("bm <number> <+-x/> <number><ENTER>\n");
      return 0;
   }
   //check if operator is valid
   if((strcmp(argv[2], "+")!=0) && (strcmp(argv[2], "-")!=0) && (strcmp(argv[2], "/")!=0) && (strcmp(argv[2], "x")!=0)){
      printf("bm <number> <+-x/> <number><ENTER>\n");
      return 0;
   }
  
   double left;
   double right;
   int i;
   int j;
   int dcounter;

   for(i=1; i<4; i+=2){
      dcounter=0;
      //check 1st element for invalid input, '-' is ok in the beginning for negative numbers
      if(((argv[i][0] < '0') || (argv[i][0] > '9')) && (argv[i][0] != '-')){
         printf("bm <number> <+-x/> <number><ENTER>\n");
         return 0;
      }
      (argv[i][0] == '.') && (dcounter+=1);         //check 1st element for decimal
      for(j=1; j<strlen(argv[i]); j++){                //check the rest of the array for invalid input
         (argv[i][j] == '.') && (dcounter+=1);
         if(dcounter>1){                                        //if more than 1 decimal
            printf("bm <number> <+-x/> <number><ENTER>\n");
            return 0;
         }
         if((argv[i][j] < '0' || argv[i][j] > '9') && argv[i][j] != '.'){
            printf("bm <number> <+-x/> <number><ENTER>\n");
            return 0;
         }
      }
   }
   left=atof(argv[1]);
   right=atof(argv[3]);
   (argv[2][0]=='+') && (printf("%g\n", left+right));
   (argv[2][0]=='-') && (printf("%g\n", left-right));
   (argv[2][0]=='x') && (printf("%g\n", left*right));
   (argv[2][0]=='/') && (printf("%g\n", left/right));
   return 0;
}

No comments:

Post a comment