C++/Simple Math

From Wikiversity

< C++
Jump to: navigation, search

Contents

[edit] Simple C++ Math

Math in C++ is very simple. Keep in mind that C++ follows the order of operations.

[edit] Adding, Subtracting, Multiplying and Dividing

#include <iostream>

using namespace std;

int main()
{
    int myInt = 100;

    myInt = myInt / 10; //myInt is now 10
    myInt = myInt * 10; //myInt is back to 100
    myInt = myInt + 50; //myInt is up to 150
    myInt = myInt - 50; //myInt is back to where it started

    cout << myInt << endl;

    cin.get();
}
//C++ arithmetic operators
// + (add)
// - (subtract)
// / (divide)
// * (multiply)
// % (modulus division) 4 % 5 = 4 the remainder is returned 6 % 5 = 1
// += (add and assign)
// -= (subtract and assign)
// /= (divide and assign)
// *= (multiply and assign)
// %= (mod and assign)

[edit] C++ math library

The C++ math library is easy to use and is accessed by including cmath.

#include <cmath>

[edit] Square Root

Now that we have the C++ math library let's use some neat functions.

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    float myFloat = 0.0f; //the f (requires decimal) tells the compiler to treat this real number as a 32 bit float
                          //and not as a 64 bit double. this is more of a force of habit than a requirement
    cout << "Enter a number. ENTER: ";
    cin >> myFloat;
    cout << "The square root of " << myFloat << " is " << sqrt(myFloat) << endl;
    cin.clear();
    cin.sync();
    cin.get();

    return 0;
}

[edit] Where To Go Next

Topics in C++
Beginners Data Structures Advanced
Part of the School of Computer Science