C++ provides various built-in functions that simplify mathematical computations. These functions help find maximum and minimum values, calculate square roots, round numbers, and compute logarithms.
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
C++
x
using namespace std;
int main() {
cout << "Max speed: " << max(220, 180); // Returns 220
return 0;
}
Example: Finding the Lowest Value
C++
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
C++
// Required for math functions
using namespace std;
int main() {
cout << "Square root of engine displacement: " << sqrt(1000); // Returns approximately 31.62
return 0;
}
Example: Rounding a Number
C++
using namespace std;
int main() {
cout << "Rounded top speed: " << round(199.7); // Returns 200
return 0;
}
Example: Calculating a Logarithm
C++
using namespace std;
int main() {
cout << "Logarithm of 2 horsepower units: " << log(2); // Returns ~0.693
return 0;
}