To help us solve mathematical functions, we can use a variety of libraries, depending on our goals. The main library is math.h (https://cppreference.com/w/c/header/math.html).
If we also want to include math with complex numbers, we can use complex.h and/or tgmath.h libraries.
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 |
/** * File: math.c * Author: Risto Heinsar * Created: 05.10.2015 * Modified: 26.09.2021 * * Description: Some example use of math.h library. * * Note: To use math.h library You must compile the program with the * linker flag "-lm", without quotes. In geany, you can add the -lm * to build path under build -> set build commands. */ #include <stdio.h> #include <math.h> int main(void) { // Integer division leads to integer answers with decimal places truncated printf("5 / 10 is %d\n", 5 / 10); printf("10 / 10 is %d\n", 10 / 10); printf("28 / 10 is %d\n\n", 28 / 10); // To get deimal places, at least one operand has to be float/double printf("9.0 / 10 is %.2f\n", 9.0 / 10); printf("9 / 10.0 is %.2f\n", 9 / 10.0); printf("Using typecasting: 9 / 10 is %.2f\n\n", 9 / (float)10); float num1 = 9; float num2 = -5.4f; float num3 = pow(num1, 2); // Using math.h functions printf("Num1 squared is %.2f\n", pow(num1, 2)); printf("Num1 squared can be also found like this: %.2f\n", num3); printf("Number 7 to the power of 3 is: %.2f\n", pow(7, 3)); printf("The square root of num1 is: %.2f\n", sqrt(num1)); printf("Alternative square root: %.2f\n", pow(num1, 1.0/2.0)); float equation = num1 * pow(num2, 2) + sqrt(num1); printf("The solution for the equation %.3f\n", equation); return 0; } |
Notice the following
- When compiling the program, we must specify an additional build argument (-lm) to the compiler. This links the mathematics library to our program.
- Math functions typically return their result. If you want to use the result later on, you need to store the result in a variable. If however you only need it as a part of a larger equation, you can use it in-place without separately storing the result.
- To get n-th root, we can use the properties of power. Make sure to use floats for the division (e.g. 1.0 instead of 1). This is necessary due to integer division truncating the decimal places.