Code:
#include <stdio.h>
#define MAXLINE 1024
int add(int, int);
int subtract(int, int);
int multiply(int, int);
int divide(int, int);
float result = 0.0;
int add (int a, int b) {
result = a + b;
return result;
}
int subtract (int a, int b) {
result = a - b;
return result;
}
int multiply (int a, int b) {
result = a * b;
return result;
}
int divide (int a, int b) {
result = a / b;
return result;
}
int main() {
int x, y;
char z[4]; //holds an integer up to 3 digits big.
printf("Please enter first integer: ");
fgets(z, MAXLINE, stdin);
x = atoi(z); //converts string to int.
printf("Now enter another integer: ");
fgets(z, MAXLINE, stdin);
y = atoi(z); //converts string to int.
printf("\nNow which operation would you like to perform with two integers?\n");
printf("Press 'a' for addition\nPress 's' for substraction\n");
printf("Press 'm' for multiplication\nPress 'd' for division\n");
printf("> ");
fgets(z, MAXLINE, stdin);
switch (z[0]) {
case 'a': case 'A':
add(x, y);
printf("Addition: %d + %d = %.2f\n", x, y, result);
break;
case 's': case 'S':
subtract(x, y);
printf("Subtraction: %d - %d = %.2f\n", x, y, result);
break;
case 'm': case 'M':
multiply(x, y);
printf("Multiplication: %d * %d = %.2f\n", x, y, result);
break;
case 'd': case 'D':
divide(x, y);
printf("Division: %d / %d = %.2f\n", x, y, result);
break;
default:
printf("I'm sorry, the key you typed in was not in operation menu. Please try again!\n");
}
return 0;
}
Above I defined MAXLINE to be 1024 to be the max length of the buffer to be read from stdin. I also added char z[4] to be an array that can hold up to an integer 3 digits big (this includes the \0 null terminator at the end of the string that is read in fgets).