FANDOM


/* Programming project 2 -- Calculator */
/* Kevin Duke - James Shirley - Mon Nov 2 2009 */
/* This is a simple calculator program that accepts the +, -, *, /, and ^ operators and Q/q for quitting. The total starts at 0 and continues to add onto that sum with each operation */

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <ctype.h>

/* Each of these functions performs a type of operation by taking in the initialvalue parameter from main and using the operator and operand found from a scanf in the functions */

/* Function for addition */
double add_function(double initialvalue)
{
/* Declaration of local variables */
  double aftervalue, operatorvalue;
/* Scan in the operand */
  scanf("%lf", &operatorvalue);
/* Take the initialvalue and add the value of the operand to it and store in the aftervalue variable */
  aftervalue = ( initialvalue + operatorvalue );
  return aftervalue;
}

/* Function for subtraction */
double subtract_function(double initialvalue)
{
  double aftervalue, operatorvalue;
  scanf("%lf", &operatorvalue);
  aftervalue = ( initialvalue - operatorvalue );
  return aftervalue;
}

/* Function for multiplication */ 
double multiply_function(double initialvalue)
{
  double aftervalue, operatorvalue;
  scanf("%lf", &operatorvalue);
  aftervalue = ( initialvalue * operatorvalue );
  return aftervalue;
}

/* Function for division */
double divide_function(double initialvalue)
{
  double aftervalue, operatorvalue;
  scanf("%lf", &operatorvalue);
  aftervalue = ( initialvalue / operatorvalue );
  return aftervalue;
}

/* Function for powers */
double power_function(double initialvalue)
{
  double aftervalue, operatorvalue;
  scanf("%lf", &operatorvalue);
  aftervalue = (pow( initialvalue, operatorvalue) );
  return aftervalue;
}

/* Start of the main function */
int main (void)
{
/* Declaration of local variables */
char operator;
double valuetotal, aftervalue, initialvalue;

/* Initialization of local variables */
initialvalue = 0;
aftervalue = 0;


  for (;;)
 {
   scanf("%c", &operator);
 
   if (tolower(operator) == 'q')
 {
   break;
 }
 
   else if (operator == '+')
{
   valuetotal= add_function( valuetotal);
   printf("The value so far is %.1f\n", valuetotal);
}


else if (operator == '-')
{
  valuetotal= subtract_function(valuetotal);
  printf("The value so far is %.1f\n", valuetotal);
}

else if (operator == '*')
{
  valuetotal= multiply_function(valuetotal);
  printf("The value so far is %.1f\n", valuetotal);
}

else if (operator == '/')
{
  valuetotal= divide_function( valuetotal);
  printf("The value so far is %.1f\n", valuetotal);
}

else if (operator == '^')
{
  valuetotal= power_function( valuetotal);
  printf("The value so far is %.1f\n", valuetotal);
}

else
  printf("Invalid operator\n");

scanf("%c", &operator);
}

printf("The total is %.1f\n", valuetotal);

return 0;

}