simple printing calculator in C doesn't work
Hello everyone,
I am new to C and don't have a programming background. So I'm trying to learn C as my first step into programming. Here is the problem I am confronted with (my code below):
Write a program that acts as a simple "printing" calculator. The program should allow the user to type in expressions of the form number operator
The following operators should be recognized by the program:
+ - * / S E
The s operator tells the program to set the "accumulator" to the typed-in number. The E operator tells the program that execution is to end. The arithmetic operations are performed on the contents of the accumulator with the number that was keyed in acting as the second operand.
This is what I came up with but it doesn't work. It compiles fine (using gcc -Wall -o ...) but doesn't do what I want it to.
Thanks for taking a look at it and letting me know where I made a mistake. :o
Code:
#include <stdio.h>
int main (void)
{
float val, tmp;
char acc;
printf("Beginning Calculations. \n");
printf("Set initial value of accumulator.\n");
printf("Use 's' to store value in accumulator.\n");
printf("Example: 10 s stores the value 10 in the accumulator.\n");
printf("Use 'e' to end program.\n");
scanf("%f%c", &val, &acc);
do {
switch (acc)
{
case 's':
tmp = val;
break;
case '+':
printf("%.f\n", tmp + val);
tmp = tmp + val;
printf("= %.2f\n", tmp);
break;
case '-':
printf("%.2f\n", tmp - val );
tmp = tmp - val;
printf("= %.2f\n", tmp);
break;
case '*':
printf("%.2f\n", tmp * val);
tmp = tmp * val;
printf("= %.2f\n", tmp);
break;
case '/':
if (val == 0)
printf("Division by zero not possible.\n");
else
printf("%.2f\n", tmp / val);
tmp = tmp / val;
printf("= %.2f\n", tmp);
break;
case 'e':
printf("Good day!\n");
break;
default:
printf("Unknown operator.\n");
break;
}
}
while (acc != 'e');
return 0;
}