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 |
/** * File: math.c * Author: Risto Heinsar * Created: 05.10.2015 * Modified: 06.10.2015 * * Description: some sample commands from math.h library. The math functions * are called in different ways, but they end up having the same result. * 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) { float num1 = 9; float num2 = -5.4; float num3 = pow(num1, 2); float equation = num1 * pow(num2, 2) + sqrt(num1); printf("Num1 squared is %f\n", pow(num1, 2)); printf("Num1 squared can be also found like this: %f\n", num3); printf("Number 7 to the power of 3 is: %f\n", pow(7, 3)); printf("The square root of num1 is: %f\n", sqrt(num1)); printf("The square root can also be found like this: %f\n", pow(num1, 1.0/2.0)); printf("The solution for the equation %f\n", equation); return 0; } |
Takeaway
- We’ll be using the word function more and more. So far, we’ve taken it for granted and haven’t paid attention to what it means. We’ve used functions like printf() and scanf().
In essence, a function is just a set of commands to carry out some goal (execute a set of commands to achieve the goal). For an example, it can be just to show some text on the screen or it can be to find the square root of a number. - So far we’ve used variables to print some numbers stored in variables using the printf() function, however we can also use functions themselves as arguments to find and print a value.
E.g. the square root function returns a number it calculates and we can either store it in a variable or directly print it out without storing it.
The same goes for power function. - To find the N-th root of a number, we can use the properties of powers as it’s done on the line 27. It’s important to use a fraction format here (1 -> 1.0). It’s because of how computers handle integers and floating point numbers.
- When using addition functions (powers, roots, sin, cos, tan, etc.) in equations, the results of those functions are found (returned) and “replaced” into the equation. This property helps us to also use them directly in printouts without storing them.