C & C++ is good to operate in mathematical operations because of its wide variety of variable definitions, wise memory usage and it’s operators in mathematics. C++ has a lot of mathematical functions that you can do mathematical tasks. Some operators may work with integers, some works with floating numbers, most are usable with both integer and floating (or double) numbers. All functions can be found in the <cmath>
library, so you must include this library before using these functions, like this.
1 2 3 |
#include <cmath> |
Also note that some of compilers may require options to use these mathematical operands. (i.e in GNU C/C++ you must use -lm option)
Here are some of mathematical functions used in C++;
pow(), powf() and powl()
pow functions are are used to find power of double floating numbers, example below results a power b,
1 2 3 4 5 |
int a = 7; int b = 2; int c = pow( a, b); |
powf() is used for floating numbers and powl() is used for long floating numbers.
sqrt() and cbrt(),
sqrt() function is used to get square root of a given value, see below,
1 2 3 4 |
float a = 16; float sq = sqrt(a); |
cbrt() is used to get cubic root of a given value
1 2 3 4 |
float a = 27; float cb = cbrt(a); |
round(), floor() and ceil()
round() function returns rounds of number
floor() function returns the given value rounded down to its nearest integer
ceil() function returns the given value rounded up to its nearest integer
1 2 3 4 5 6 |
float a = 7.49; int b = floor(a); int c = ceil(a); int r = round(a); |
min() and max()
min() and max() functions are used to find minimum and maximum number of pairs
1 2 3 4 5 |
int a = 8, b = 11; int c = max( a, b); int d = min( a, b); |
abs() and fabs(), Absolute
1 2 3 4 5 6 7 |
int a = -7; int b = abs( a); float f = -7.2; float g = fabs(f); |
Trigonometric Functions
Here we listed some of trigonometric functions below,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
float x=0.1; float a = sin(x); float b = cos(x); float c = tan(x); float e = asin(a); float f = acos(b); float g = atan(c); float h = sinh(e); float i = cosh(f); float j = tanh(g); flaot k = exp(x); float l = log(x); |
All of these functions and more can be found in cmath library.
In addition to these functions, In C++ Builder, VCL and FMX applications have most of these functions starts with upper case i.e. Max(), Min(), Sin(), Cos() etc.
Finally library also has some constants, i.e Pi number which is used to calculate peripheral and circular area of a circle as below,
1 2 3 4 5 |
float radius = 5.0; float peripheral = 2*M_PI*radius; float circular_area = M_PI*radius*radius; |