IVS-calculator
Loading...
Searching...
No Matches
mathlib.cpp
Go to the documentation of this file.
1#include "mathlib.h"
2#include <cmath>
3
4namespace mathlib {
5
9double add(double a, double b) {
10
11 return a + b;
12}
13
17double subtract(double a, double b) {
18
19 return a - b;
20}
21
25double multiply(double a, double b) {
26
27 return a * b;
28}
29
33double divide(double a, double b, MathError &err) {
34
35 if(b == 0) {
36 err = DIVISION_BY_ZERO;
37 return 0;
38 }
39
40 err = OK;
41 return a / b;
42}
43
47double factorial(int a, MathError &err) {
48
49 if(a < 0 ) {
51 return 0;
52 }
53
54 err = OK;
55
56 double result = 1;
57 for(int i = 1; i <= a; i++) {
58 result = result * i;
59 }
60
61 return result;
62}
63
67double power(double base, int exp) {
68
69 if(exp == 0) {
70 return 1;
71 }
72
73 double result = 1;
74
75 for(int i = 0; i < exp; i++) {
76 result = result * base;
77 }
78
79 return result;
80}
81
85double root(double base, int n, MathError &err) {
86
87 if(n == 0) {
88 err = INVALID_ROOT;
89 return 0;
90 }
91 if(n < 0) {
92 err = INVALID_ROOT;
93 return 0;
94 }
95 if(base < 0 && n % 2 == 0) {
96 err = INVALID_ARGUMENT;
97 return 0;
98 }
99 if(base < 0 && n % 2 != 0) {
100 err = OK;
101 return -std::pow(-base, 1.0 / n);
102 }
103
104 err = OK;
105 return std::pow(base, 1.0 / n);
106}
107
111double modulo(double a, double b, MathError &err) {
112
113 if(b == 0) {
114 err = DIVISION_BY_ZERO;
115 return 0;
116 }
117
118 err = OK;
119
120 return std::fmod(a, b);
121}
122}
Mathematical library for calculator project.
double root(double base, int n, MathError &err)
Implementation of function root.
Definition mathlib.cpp:85
double add(double a, double b)
Implementation of function add.
Definition mathlib.cpp:9
double multiply(double a, double b)
Implementation of function multiply.
Definition mathlib.cpp:25
double modulo(double a, double b, MathError &err)
Implementation of function modulo.
Definition mathlib.cpp:111
MathError
Definition mathlib.h:11
@ INVALID_ROOT
Definition mathlib.h:15
@ NEGATIVE_FACTORIAL
Definition mathlib.h:14
@ DIVISION_BY_ZERO
Definition mathlib.h:13
@ INVALID_ARGUMENT
Definition mathlib.h:16
double divide(double a, double b, MathError &err)
Implementation of function divide.
Definition mathlib.cpp:33
double subtract(double a, double b)
Implementation of function subtract.
Definition mathlib.cpp:17
double factorial(int a, MathError &err)
Implementation of function factorial.
Definition mathlib.cpp:47
double power(double base, int exp)
Implementation of function power.
Definition mathlib.cpp:67