I am trying to make a simple calculator that will take a value and perform an operator on the value multiple times for example
result = 0.0
+5
result + 5.0 = 5.0
new result = 5.0
*2.2
result * 2.2 = 11.0
updated result = 11.0
I have created a while with a conditional if statement. The if statement works fine the first cycle but after the fist cycle it defaults to the else statement.
Can anyone please help me figure this out. Thanks much!
Code:
#include <stdio.h>
double calculate(double currentVal, char operatorInput, double inputVal);
int main(){
int done = 0;
double newResult = 5;
double inputVal;
char operatorInput;
printf(" simple calculator \n");
printf("**********************************************************\n");
printf("Calculator is on.\n");
printf("result = %.1f\n", newResult);
while (!done) {
printf("input agian\n");
scanf("%c%lf", &operatorInput, &inputVal);
if (operatorInput == '*' || operatorInput == '/' || operatorInput == '+' || operatorInput == '-') {
newResult = calculate(newResult, operatorInput, inputVal);
printf("result %c %.1lf = %.1lf\n", operatorInput, inputVal, newResult);
printf("new result = %.1f\n", newResult);
}
else {
printf("UnknownOperatorException is thrown\n");
printf("Please re-enter input:\n");
}
}
return 0;
}
double calculate(double currentVal, char operatorInput, double inputVal){
// a (x) b = c
double a, b, c;
char x;
a = currentVal;
x = operatorInput;
b = inputVal;
if (x == '*'){
c = a * b;
}
else if(x == '/'){
c = a / b;
}
else if(x == '+'){
c = a + b;
}
else if(x == '-'){
c = a - b;
}
return c;
}