-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmath_ops.c
95 lines (80 loc) · 1.79 KB
/
math_ops.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
#include "monty.h"
/**
* Add - performs addition operations
*
* @stack: a stack.
* @number: line number.
*/
void Add(stack_t **stack, unsigned int number)
{
int sum;
if (stackLen(*stack) < 2)
ErrExit(*stack, "L%d: can't add, stack too short\n", number);
sum = fpop(stack) + fpop(stack);
fpush(stack, sum);
}
/**
* Sub - performs subtraction operations
*
* @stack: a stack.
* @number: line number.
*/
void Sub(stack_t **stack, unsigned int number)
{
int difference, tmp;
if (stackLen(*stack) < 2)
ErrExit(*stack, "L%d: can't sub, stack too short\n", number);
tmp = fpop(stack);
difference = fpop(stack) - tmp;
fpush(stack, difference);
}
/**
* Mul - performs multiplication operations
*
* @stack: a stack.
* @number: line number.
*/
void Mul(stack_t **stack, unsigned int number)
{
int product;
if (stackLen(*stack) < 2)
ErrExit(*stack, "L%d: can't mul, stack too short\n", number);
product = fpop(stack) * fpop(stack);
fpush(stack, product);
}
/**
* Div - performs division operations
*
* @stack: a stack.
* @number: line number.
*/
void Div(stack_t **stack, unsigned int number)
{
int top;
int quotient;
if (stackLen(*stack) < 2)
ErrExit(*stack, "L%d: can't div, stack too short\n", number);
if (getTop(*stack) == 0)
ErrExit(*stack, "L%d: division by zero\n", number);
top = fpop(stack);
quotient = fpop(stack) / top;
fpush(stack, quotient);
}
/**
* Mod - performs modulus operations
*
* @stack: a stack.
* @number: line number.
*/
void Mod(stack_t **stack, unsigned int number)
{
int top;
int remainder;
if (stackLen(*stack) < 2)
ErrExit(*stack, "L%d: can't mod, stack too short\n", number);
if (getTop(*stack) == 0)
ErrExit(*stack, "L%d: division by zero\n", number);
top = fpop(stack);
remainder = fpop(stack) % top;
fpush(stack, remainder);
}