Calculator Challenge:
C
Easy
4 views
Problem Description
Input two numbers and one operator (+, -, *, /) from the user. If the operator is invalid or division by zero then give a proper error message and input the operator again. Program should run until the user presses 'q'.
Official Solution
#include <stdio.h>
int main() {
double num1, num2, result;
char op;
while (1) {
printf("nEnter two numbers (or press q to quit): ");
// Check if user wants to quit
if (scanf("%lf %lf", &num1, &num2) != 2) {
scanf(" %c", &op);
if (op == 'q' || op == 'Q') {
printf("Program terminated.n");
break;
} else {
printf("Invalid input.n");
// Clear input buffer
while (getchar() != 'n');
continue;
}
}
while (1) {
printf("Enter operator (+, -, *, /) or q to quit: ");
scanf(" %c", &op);
if (op == 'q' || op == 'Q') {
printf("Program terminated.n");
return 0;
}
if (op == '+') {
result = num1 + num2;
break;
} else if (op == '-') {
result = num1 - num2;
break;
} else if (op == '*') {
result = num1 * num2;
break;
} else if (op == '/') {
if (num2 == 0) {
printf("Error: Division by zero is not allowed.n");
} else {
result = num1 / num2;
break;
}
} else {
printf("Error: Invalid operator.n");
}
}
printf("Result: %.2lfn", result);
}
return 0;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!