Using Math.h Functions in C
In the examples discussed below, we will be using the three most common functions of the “math.h” library of the C programming language:
Example # 1: The Natural Log Function
In this example, we will be using the natural log function of the C programming language. The C script for this purpose is shown in the following image:
In this example, we have defined two double variables “x” and “result”. The value of the “x” variable is “3.2”. Then, we have saved the natural log of this variable to the “result” variable by using the “log” function of the “math.h” library. After that, we have printed this result on the terminal.
Then, to compile this script, we have used the command shown below. An important thing to be noted is that this time, we have also used the “-lm” flag with the compilation command. It is so because the C scripts containing the functions of the “math.h” header file are compiled this way. Otherwise, you will not be able to compile them.
Then, this script was executed in the regular manner with the help of the following command:
The natural log of the specified number is shown in the image below:
Example # 2: The Square Root Function
Now, we will be using the square root function of the “math.h” library. The following C script explains this:
In this script, we have defined a number “x” whose square root is to be calculated. The value of this number is “16.0”. Then, we have stored the square root of this variable inside the “result” variable by using the “sqrt” function of the “math.h” library. After that, we have displayed this result on the terminal.
The square root of the specified number is shown in the image below:
Example # 3: The Power Function
Now, we will be using the power function of the “math.h” library. The C script for this purpose is shown in the following image:
In this program, we have defined two variables “x” and “y”. The “x” variable is the one whose “yth” power is to be calculated. Then, we have another variable “result” in which we have stored the “yth” power of “x” by making use of the “pow” function of the “math.h” library. Finally, we have printed the “yth” power of “x” on the terminal.
The “yth” power of the number “x” is shown in the image below:
Conclusion
In this guide, we have only discussed three of the most commonly used functions of the “math.h” library of the C programming language. This was done to show you how this library actually works.