Write functions that compute the sum, difference, quotient, products of two numbers. Call each function inside a switch statement.
Mon May 20 2024 09:29:48 GMT+0000 (Coordinated Universal Time)
Saved by
@JC
#include <stdio.h>
float sum(float n1, float n2);
float difference(float n1, float n2);
float product(float n1, float n2);
float quotient(float n1, float n2);
int main() {
float n1, n2, total;
char op;
printf("Enter an operator: ");
scanf(" %c", &op);
printf("Enter first number: ");
scanf("%f", &n1);
printf("Enter second number: ");
scanf("%f", &n2);
switch (op) {
case '+':
total = sum(n1, n2);
printf("The sum is: %.2f\n", total);
break;
case '-':
total = difference(n1, n2);
printf("The difference is: %.2f\n", total);
break;
case '*':
case 'x':
total = product(n1, n2);
printf("The product is: %.2f\n", total);
break;
case '/':
case '÷':
total = quotient(n1, n2);
printf("The quotient is: %.2f\n", total);
break;
default:
printf("Invalid operator.\n");
}
return 0;
}
float sum(float n1, float n2) {
return n1 + n2;
}
float difference(float n1, float n2) {
return n1 - n2;
}
float product(float n1, float n2) {
return n1 * n2;
}
float quotient(float n1, float n2) {
if (n2 != 0) {
return n1 / n2;
} else {
printf("Error: Division by zero.\n");
return 0;
}
}
content_copyCOPY
Comments