Skip to content

Instantly share code, notes, and snippets.

@tudorconstantin
Created April 4, 2015 09:51
Show Gist options
  • Save tudorconstantin/7a2a7b5a64c94bac2d5e to your computer and use it in GitHub Desktop.
Save tudorconstantin/7a2a7b5a64c94bac2d5e to your computer and use it in GitHub Desktop.
a cleaner solution to the problem of creating a calculator from CS50
/* Write a program that acts as a simple calculator.The program shuld
alow the user to input data in form number operator number.
The following operators shuld pe recognized: +, -, *, /, S, E, .
The S operator tells the program to set the acumulator to the typed in
number. The E operator tells the program that execution is to end.
The artmethic operatioons are performed on the contenst of the acumulator with the number
that was keyed in accting as a smaple operand
program output
10S set Acumulator to 10
= 10.0000
2/ divide by2
= 5.0000*/
#include <stdio.h>
int main(void)
{
float acc, operand;
char operator = (char) 0;// because for some reason c doesn't like '' as an empty string initializator
acc = 0;
operand = 0;
printf("start computing\n");
while( operator != 'E')
{
if( operator == 'S'){
acc = operand;
} else if ( operator == '+') {
acc = acc + operand;
} else if ( operator == '-') {
acc = acc - operand;
}
printf ("[debug] state after the if conditions: acc=%f, operator=%c, operand=%f\n", acc, operator, operand);
printf(" = %f\n", acc);
scanf("%f %c", &operand, &operator);
printf ("[debug] state after data read: acc=%f, operator=%c, operand=%f\n", acc, operator, operand);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment