Back to Curriculum

9. Useful Math Related Functions

C++ Math Functions

C++ provides many useful math functions in the <cmath> library. Here are some commonly used ones:

  • pow(x, y) - raises x to the power of y
  • sqrt(x) - square root of x
  • abs(x) - absolute value of x
  • round(x) - rounds x to the nearest integer
  • ceil(x) - rounds x up to the nearest integer
  • floor(x) - rounds x down to the nearest integer
#include <cmath>

double result = pow(2, 3);    // 8.0 (2^3)
double root = sqrt(16);       // 4.0
double rounded = round(3.7);  // 4.0
double ceiling = ceil(3.2);   // 4.0
double floor_val = floor(3.8); // 3.0

Note: These functions return double values, so you might need to cast them if you want integers.

Your Task

Calculate the square root of 25 and store it in a variable called squareRoot. Use the sqrt() function from the <cmath> library.

🎉

Lesson Complete!

Great job! You now know how to use C++'s powerful math functions for complex calculations.

Continue to Lesson 10: Hypotenuse Calculator Practice Program
main.cpp
Output
Click "Check Answer" to run your code.