Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- /*add, subtract, multiply, divide*/
- float add(int x, int y);
- float sub(int x, int y);
- float mul(int x, int y);
- float divd(int x, int y);
- int main( int argc, char *argv[]){
- /*VARIABLE DECLARATION BLOCK*/
- int num1,num2; /*first and second numbers*/
- long opr_loc; /*operator location*/
- int ctr,ctr2,argctr; /*for loop counters*/
- /*for output*/
- int a;
- int b;
- int d; /*desicion for operator*/
- /*1 = add
- 2 = subtract
- 3 = multiply
- 4 = divide */
- char *p; /*strchr pointer*/
- char *opr1;
- char *opr2;
- char *eq_in; /*input equation*/
- /*END VARIABLE DECLARATION BLOCK*/
- /*memory allocation*/
- eq_in = malloc(128*sizeof(char));
- opr1 = malloc(128*sizeof(char));
- opr2 = malloc(128*sizeof(char));
- /*EXPLANATION FOR THE FOLLOWING CODE:
- * this for loop is used to allow spaces.
- * by looping through the arguments
- * I make 1 string with the equation in it
- * (all of the argv in one string)*/
- for(argctr = 1; argctr < argc; argctr++)
- {
- if (strcmp(argv[argctr],"*")==0)
- {
- eq_in = strcat(eq_in,"*");
- }
- else
- {
- eq_in = strcat(eq_in,argv[argctr]);
- }
- }
- /*FIND OPERATOR*/
- if (strchr(eq_in,'+') != NULL)
- {
- p = strchr(eq_in,'+');
- d = 1;
- }
- else if(strchr(eq_in,'-') != NULL)
- {
- p = strchr(eq_in,'-');
- d = 2;
- }
- else if(strchr(eq_in,'*') != NULL)
- {
- p = strchr(eq_in, '*');
- d = 3;
- }
- else if(strchr(eq_in, '/') != NULL)
- {
- p = strchr(eq_in, '/');
- d = 4;
- }
- /*END FIND OPERATOR BLOCK*/
- /*SEPERATE OPERANDS FROM OPERATOR*/
- for(ctr = 0;ctr < (p-eq_in); ctr++)
- {
- opr1[ctr] = eq_in[ctr];
- }
- ctr2 = 0;
- for(ctr = p - eq_in + 1; ctr < strlen(eq_in); ctr++)
- {
- opr2[ctr2] = eq_in[ctr];/*USES FIRST COUNTER VARIABLE*/
- ++ctr2;
- }
- /*ASCII TO INTEGER*/
- a = atoi(opr1);
- b = atoi(opr2);
- if(d == 1)
- {
- printf("%f\n",add(a,b));
- }
- else if(d == 2)
- {
- printf("%f\n",sub(a,b));
- }
- else if(d == 3)
- {
- printf("%f\n",mul(a,b));
- }
- else if(d == 4)
- {
- printf("%f\n",divd(a,b));
- }
- return 0;
- }
- float add(int x, int y)
- {
- return x + y;
- }
- float sub(int x, int y)
- {
- return x - y;
- }
- float mul(int x, int y)
- {
- return x * y;
- }
- float divd(int x, int y)
- {
- return x / y;
- }
Add Comment
Please, Sign In to add comment