C++ Tutorial

C++ Math

cmath gives sqrt, pow, round, and abs. Use them instead of writing formulas by hand.

Include cmath

Arithmetic operators handle plus, minus, times, and divide. Square roots, powers, and rounding live in the standard math library. Bring it in with #include <cmath> at the top of the file, next to iostream.

The functions take and return floating-point values in most cases. Store the result in a doubleunless you have a reason not to.

Compile the examples in /cpp/try. That is the C++ editor. Do not paste them into Python at /try or HTML at /html/try.

A complete program

This file uses the four functions you will see most often: sqrt, pow,abs, and round. Copy it, change the numbers, and compile again.

Example

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

int main() {
  double side = 9.0;
  cout << "sqrt(9) = " << sqrt(side) << endl;
  cout << "pow(2, 8) = " << pow(2.0, 8.0) << endl;
  cout << "abs(-4.5) = " << abs(-4.5) << endl;
  cout << "round(2.6) = " << round(2.6) << endl;
  return 0;
}

sqrt

sqrt(x) returns the square root of x. Pass a non-negative number. A negative argument is a domain error; many compilers print nan (not a number) instead of a useful result.

Distance formulas use square roots. The length of a right-triangle hypotenuse with legs 3 and 4 issqrt(3 * 3 + 4 * 4), which is 5.

Example

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

int main() {
  double a = 3.0;
  double b = 4.0;
  double c = sqrt(a * a + b * b);
  cout << c << endl;
  return 0;
}

pow

pow(base, exp) raises base to exp. Both arguments are treated as floating-point, so the result is a double even when the inputs look like integers.

For a small integer power you can still write n * n. Use pow when the exponent is not a tiny constant, or when you are already working in doubles.

Prefer pow(2.0, 8.0) over integer literals if you want the floating-point overload. Integerpow is not a built-in operator in C++.

abs and round

abs(x) returns the absolute value: negative numbers become positive, positive numbers stay positive. Use it when a difference might go either way and you only care about size.

round(x) returns the nearest integer as a double. Halfway cases (such as 2.5) round away from zero, so 2.5 becomes 3.0 and -2.5 becomes -3.0.

Example

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

int main() {
  cout << abs(-12.0) << endl;
  cout << abs(7.25) << endl;
  cout << round(3.2) << endl;
  cout << round(3.8) << endl;
  return 0;
}

The usual toolkit

CallMeaning
sqrt(x)Square root of x
pow(x, y)x to the power y
abs(x)Absolute value of x
round(x)Nearest integer (as double)
floor(x)Largest integer not greater than x
ceil(x)Smallest integer not less than x

floor and ceil are in the same header. You do not need them yet; know they exist so you do not reinvent them.

Types and mistakes

  • Most of these functions return double. Assigning to int truncates toward zero.
  • Do not take sqrt of a negative number if you expect a real result.
  • pow is slower than a simple multiply. For squares, write x * x.

Next: bool values, which math comparisons produce.

Worked examples

The short listings above are there so you can see the grammar. The programs here use the same statements on quantities that already have units: a speed, a pH, a count of bases. They are classroom numbers. Air resistance is ignored. g is 9.81 m/s² unless a line says otherwise.

Open them in the C++ editor at /cpp/try. Change one measurement and check whether the result still has the right unit.

Physics

Hypotenuse, then displacement

Pythagoras is also how you get the magnitude of a 2D vector. A displacement 3 m east and 4 m north has size 5 m. hypot(a, b) is the library version of sqrt(a*a + b*b).

|r| = √(x² + y²)

Example

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

int main() {
  double a = 3.0;
  double b = 4.0;
  cout << "c = " << hypot(a, b) << " m" << endl;
  return 0;
}

Maths

Roots of a quadratic

x² − 5x + 6 = 0 factors as (x − 2)(x − 3) = 0, so the roots are 2 and 3. The quadratic formula does the same job when factoring is ugly: discriminant b² − 4ac, then the two signs on the square root.

x = (−b ± √(b² − 4ac)) / (2a)

Example

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

int main() {
  double a = 1.0, b = -5.0, c = 6.0;
  double d = b * b - 4.0 * a * c;
  double x1 = (-b + sqrt(d)) / (2.0 * a);
  double x2 = (-b - sqrt(d)) / (2.0 * a);
  cout << "x = " << x1 << " and " << x2 << endl;
  return 0;
}

FAQ: C++ Math

Common questions about this page.

What is the StudyGrid C++ tutorial?

The StudyGrid C++ tutorial is a full beginner-to-advanced track: syntax, types, input, loops, functions, classes, the STL, templates, maps, and lambdas. Each chapter has copy-and-run examples.

Should I run c++ math examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn c++ math in this C++ C++ lesson (C++ Math).

Is the C++ editor the same as Try Python or Try HTML?

No. Try C++ compiles with g++ at /cpp/try and shows stdout plus compiler messages. Try Python stays at /try. Try HTML stays at /html/try. C++ lessons never open those editors.

Do I need to install a compiler to learn C++?

No. Open a chapter, click Try it in C++, and compile in the browser. You can also download a .cpp file and compile locally with g++.

Where should I start the C++ tutorial?

Start at C++ Intro, then Get Started and Syntax. After the first program, continue to output, variables, and if-else. After classes, open C++ Examples, then templates, map, and lambdas. Use Next at the bottom of each chapter.

Is the C++ tutorial free?

Yes. The C++ workshop on StudyGrid (studygrid.in) is free: dashboard, chapters, and the compile-and-run editor.