Skip to content

Instantly share code, notes, and snippets.

@Feliix42
Created October 28, 2015 11:33
Show Gist options
  • Save Feliix42/1d78b50a40276c1f93f3 to your computer and use it in GitHub Desktop.
Save Feliix42/1d78b50a40276c1f93f3 to your computer and use it in GitHub Desktop.
The calculator task from the c lessons.
#include <stdio.h>
int main(void) {
int a, b;
char operation;
// get the numbers from the console
printf("Enter the first number: ");
scanf("%d", &a);
printf("Enter the second number: ");
scanf("%d", &b);
/*
* Get the Operation
* NOTE: C doesn't flush the memory and takes the `return` from the second
* number as input for the operation. You can solve this by putting
* a space in front of the %c placeholder. This will ignore all
* whitespace characters (including `return`).
*/
printf("Enter a operation: ");
scanf(" %c", &operation);
int erg;
float ergfloat;
switch (operation) {
case '+':
// Addition
erg = a + b;
printf("The sum of both numbers is %d.\n", erg);
break;
case '-':
// Subtraction
erg = a - b;
printf("The difference of both numbers is %d.\n", erg);
break;
case '*':
// Multiplication
erg = a * b;
printf("The product of both numbers is %d.\n", erg);
break;
case '/':
// Division -> (float) var casts a variable from int to float (temporarily)
ergfloat = (float) a / (float) b;
printf("The quotient of both numbers is %f.\n", ergfloat);
break;
case '%':
// Modulo
erg = a % b;
printf("%d mod %d is %d.\n", a, b, erg);
break;
default:
// Default Case
printf("You entered a wrong operation!\n");
break;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment