-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.c
More file actions
110 lines (98 loc) · 2.56 KB
/
main.c
File metadata and controls
110 lines (98 loc) · 2.56 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
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
105
106
107
108
109
110
#include <stdio.h>
#ifndef bool
typedef enum Boolean
{false = 0, true = 1}
bool;
#endif
typedef enum Operator
{Add, Subtract, Multiply, Divide, Power} operator;
void CalcInit();
void CalcInit2(double fResults);
double GetInput();
int GetOperator();
double Calculate();
double Pow();
double num1;
double num2;
operator Operator;
double result;
int main() {
int continueCalc = 1;
while (continueCalc)
{
CalcInit();
printf("\nTry again? (1 for yes, any other input for no.): ");
getchar();
if (scanf("%d", &continueCalc) != true) {
getchar();
continueCalc = 0;
}
}
}
void CalcInit() {
printf("\nWelcome To The Terminal Calculator!");
printf("\nInput #1: ");
num1 = GetInput(num1);
printf("\nInput #2: ");
num2 = GetInput(num2);
printf("\nInputs: %.8g, %.8g\n", num1, num2);
printf("Operator (Add = 0, Subtract = 1, Multiply = 2, Divide = 3, Pow = 4): ");
Operator = GetOperator(Operator);
printf("Calculating...");
result = Calculate();
printf("\nThe result is: %.8g!",result);
}
void CalcInit2(double fResults) {
printf("\nWelcome To The Terminal Calculator!");
printf("\nInput #1: %lf", fResults);
num1 = fResults;
printf("\nInput #2: ");
num2 = GetInput(num2);
printf("\nInputs: %.8g, %.8g\n", num1, num2);
printf("Operator (Add = 0, Subtract = 1, Multiply = 2, Divide = 3, Pow = 4): ");
Operator = GetOperator(Operator);
printf("Calculating...");
result = Calculate();
printf("\nThe result is: %.8g!",result);
}
double GetInput(double num) {
if (scanf("%lf", &num) == (false)) {
printf("Invalid input, try again.\n");
getchar();
GetInput(num);
}
return num;
}
int GetOperator(int num) {
bool valid = (scanf("%d", &num));
if (valid == false || num > 4 || num < 0) {
printf("Invalid input, try again.\n");
int num2;
GetOperator(num);
}
return num;
}
double Calculate() {
if (Operator == Add) {return num1 + num2;}
if (Operator == Subtract) {return num1 - num2;}
if (Operator == Multiply) {return num1 * num2;}
if (Operator == Divide) {return num1 / num2;}
if (Operator == Power) {return Pow(num1, num2);}
return 0;
}
double Pow(double num, double pow) {
double result = num;
if (pow > 0) {
for (int i = 1; i < pow; i++)
{
result *= num;
}
}
else if (pow < 0)
for (int i = 1; i > pow; i--)
{
result *= 1/num;
}
else result = 1;
return result;
}