c_winter_2019/calculator.c

157 lines
3.3 KiB
C
Raw Normal View History

2020-01-31 14:49:37 +01:00
#include <stdio.h>
/**
* calculate the sum of two numbers
* @param number1 first summand
* @param number2 second summand
* @return sum of the two summands
*/
int add(int number1, int number2);
/**
* calculate the product of two numbers
* @param number1 first factor
* @param number2 second factor
* @return product of the two factors
*/
float multiply(int number1, float number2);
/**
* calculate the power of two integers
* @param number1 basis
* @param number2 exponent
* @returns number1 to the power of number2
*/
int power(int number1, int number2);
/**
* calculate the remainder of the division of two numbers
* @param number1 divident
* @param number2 divisor
* @returns number1 modulo number2
*/
int modulo(int number1, int number2);
/**
* calculate the factorial
* @param number number to calculate factorial of
* @return number!
*/
int factorial(int number);
/**
* calculate a fibonacci number
* @param number what fibonacci number should be computed?
* @returns numberth fibonacci number
*/
int fib(int number);
int main(void) {
int number1;
int number2;
char operator;
printf("give me two numbers and an operator seperated by spaces\n");
int n_matched = scanf("%d %c %d", &number1, &operator, &number2);
if (n_matched != 3) {
printf("Failure!\n");
return 1;
}
switch (operator) {
case '+':
case 'a':
case 'A':
printf("%d\n", add(number1, number2));
break;
case '-':
case 's':
case 'S':
printf("%d\n", add(number1, -number2));
break;
case '*':
case 'm':
case 'M':
printf("%d\n", multiply(number1, number2));
break;
case '/':
case 'd':
case 'D':
printf("%f\n", multiply(number1, 1.0 / number2));
break;
case '%':
case 'r':
case 'R':
printf("%d\n", modulo(number1, number2));
break;
default:
printf("are you stupid? thats not an operator!!!1\n");
break;
}
return 0;
}
int add(int number1, int number2) {
return number1 + number2;
}
float multiply(int number1, float number2) {
/* recursive approach */
if (number1 == 0) {
return 0;
}
return number2 + multiply(number1-1, number2);
/* looping approach */
float multiple = 0;
for (int i = 0; i < number1; ++i) {
multiple += number2;
}
return multiple;
/* trivial approach */
return number1 * number2;
}
int power(int number1, int number2) {
/* looping approach */
int power_value = 1;
for (int i = 0; i < number2; ++i) {
power_value *= number1;
}
return power_value;
/* recursive approach */
if (number2 == 0) {
return 1;
}
return multiply(number1,power(number1, number2 - 1));
}
int modulo(int number1, int number2) {
return number1 % number2;
}
int factorial(unsigned number) {
if (number == 0) {
return 1;
}
return number * factorial(number - 1);
}
int fib(unsigned number) {
if (number == 0) {
return 0;
}
if (number == 1) {
return 0;
}
if (number == 2) {
return 1;
}
return fib(number - 1) + fib(number - 2);
}