C++ Math

C++ provides various built-in functions that simplify mathematical computations. These functions help find maximum and minimum values, calculate square roots, round numbers, and work with logarithms.

Tutorials dojo strip



Finding Maximum and Minimum Values

To compare two numbers and determine the larger or smaller value, C++ offers the max() and min() functions.

Example: Finding the Highest Value

#include <iostream>
using namespace std;

int main() {
    cout << "Max speed: " << max(220, 180);  // Returns 220
    return 0;
}


Example: Finding the Lowest Value

#include <iostream>
using namespace std;

int main() {
    cout << "Lowest fuel capacity: " << min(15, 20);  // Returns 15
    return 0;
}




Using the <cmath> Library

For more advanced math operations, C++ provides the <cmath> library, which contains functions such as square root (sqrt()), rounding (round()), and logarithm (log()).

Example: Square Root Calculation

#include <iostream>
#include <cmath>  // Required for math functions
using namespace std;

int main() {
    cout << "Square root of engine displacement: " << sqrt(1000);  // Returns 31.62
    return 0;
}


Example: Rounding a Number

#include <iostream>
#include <cmath>
using namespace std;

int main() {
    cout << "Rounded top speed: " << round(199.7);  // Returns 200
    return 0;
}


Example: Calculating a Logarithm

#include <iostream>
#include <cmath>
using namespace std;

int main() {
    cout << "Logarithm of 2 horsepower units: " << log(2);  // Returns ~0.693
    return 0;
}

Tutorials dojo strip
Scroll to Top