-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalculator.c
More file actions
61 lines (54 loc) · 1.84 KB
/
calculator.c
File metadata and controls
61 lines (54 loc) · 1.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <stdio.h>
int main(void) {
int choice;
double num1, num2;
while (1) {
printf("\n===== Basic Calculator =====\n");
printf("1. Addition (+)\n");
printf("2. Subtraction (-)\n");
printf("3. Multiplication (*)\n");
printf("4. Division (/)\n");
printf("5. Exit\n");
printf("Enter your choice (1-5): ");
if (scanf("%d", &choice) != 1) {
// clear invalid input from stdin
int c;
while ((c = getchar()) != '\n' && c != EOF) { }
printf("Invalid choice. Please enter a number between 1 and 5.\n");
continue;
}
if (choice == 5) {
printf("Goodbye!\n");
break;
}
printf("Enter two numbers separated by space: ");
if (scanf("%lf %lf", &num1, &num2) != 2) {
int c;
while ((c = getchar()) != '\n' && c != EOF) { }
printf("Invalid numbers. Try again.\n");
continue;
}
switch (choice) {
case 1:
printf("%.6f + %.6f = %.6f\n", num1, num2, num1 + num2);
break;
case 2:
printf("%.6f - %.6f = %.6f\n", num1, num2, num1 - num2);
break;
case 3:
printf("%.6f * %.6f = %.6f\n", num1, num2, num1 * num2);
break;
case 4:
if (num2 == 0.0) {
printf("Error: Division by zero is not allowed.\n");
} else {
printf("%.6f / %.6f = %.6f\n", num1, num2, num1 / num2);
}
break;
default:
printf("Invalid choice. Please select between 1 and 5.\n");
break;
}
}
return 0;
}