-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
104 lines (93 loc) · 1.98 KB
/
main.c
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
#include <ctype.h>
#include <math.h>
// Function prototypes
void start();
float getNumber();
char getOperator();
float calculate(float num1, char operator, float num2);
bool calculateAgain();
int main()
{
start();
return 0;
}
void start()
{
do
{
float num1 = getNumber();
char operator= getOperator();
float num2 = getNumber();
float result = calculate(num1, operator, num2);
printf("Result is: %.2f\n", result);
} while (calculateAgain());
printf("Thank you for using a calculator.\n");
}
float getNumber()
{
float num;
while (true)
{
num = get_float("Enter a number: ");
if (!isnan(num))
{
break;
}
printf("Invalid input. Please enter a valid number.\n");
}
return num;
}
char getOperator()
{
char operator;
while (true)
{
operator= get_char("Enter an operator (+, -, *, /): ");
if (operator== '+' || operator== '-' || operator== '*' || operator== '/')
{
break;
}
printf("Invalid operator. Please enter one of +, -, *, /.\n");
}
return operator;
}
float calculate(float num1, char operator, float num2)
{
switch (operator)
{
case '+':
return num1 + num2;
case '-':
return num1 - num2;
case '*':
return num1 * num2;
case '/':
if (num2 == 0)
{
printf("Cannot divide by zero\n");
return 0;
}
return num1 / num2;
default:
printf("Invalid operator\n");
return 0;
}
}
bool calculateAgain()
{
char choice;
while (true)
{
choice = get_char("Do you want to calculate again? (y/n): ");
choice = tolower(choice);
if (choice == 'y' || choice == 'n')
{
break;
}
printf("Invalid input. Please enter 'y' for yes or 'n' for no.\n");
}
return choice == 'y';
}