Simple math in C++: Difference between revisions

wikademia>Cybiko123
mNo edit summary
wikademia>Reinterpret cast
Line 1: Line 1:
== Simple C++ Math ==
== Simple C++ Math ==


So, first things first. Lets add the math libraries to our C++ project. That way we have the ability to do useful math functions such as powers, square roots and the like.
So, first things first. Lets add the math libraries to our C++ project. That way we have the ability to do useful math functions such as powers, square roots and the like.  


<code><pre>
<code><pre>
#include <math>
#include <cmath> // ANSI C++ way. For ANSI C you should do: #include <math.h>
</pre></code>
</pre></code>


Note that the math library is one of the 18 ANSI C language standard libraries that can be imported in C++.
Now you have made many useful functions available to your program. Now, let's do some math.
Now you have made many useful functions available to your program. Now, let's do some math.


Line 29: Line 30:
int five=5, six=6, twelve=12;
int five=5, six=6, twelve=12;
float pi=3.14, myResult;
float pi=3.14, myResult;
myResult = (float)six * pi + (float)twelve;
myResult = six * pi + twelve; // since pi is float, no need to cast six and twelve to float
myResult = myResult - (float)five;
myResult = myResult - five;
</pre></code>
</pre></code>


Line 66: Line 67:
</pre></code>
</pre></code>


Let's investigate what this does. First, this program takes the square root of 25 and stored into myResult. This leaves a 5.00 in myResult. Then this value is squared and stored back into itself. This means 25.00 will be stored in myResult. Notice that I have put 2.00 into the power function. If I was to put just a 2, then the output number would be an integer, and not a float. So, more simply:
Let's investigate what this does. First, this program takes the square root of 25 and stored into myResult. This leaves a 5.00 in myResult. Then this value is squared and stored back into itself. This means 25.00 will be stored in myResult. So, more simply:


<code><pre>
<code><pre>
Line 72: Line 73:
</pre></code>
</pre></code>


For a list of functions, see [http://en.wikipedia.org/wiki/Math.h math.h].
=== End of lesson 3 ===
=== End of lesson 3 ===