Site Tools


wiki:hpp-numbers

Table of Contents

<numbers>

<numbers> provides mathematical constants (C++20): std::numbers::pi, std::numbers::e, std::numbers::sqrt2, etc. The constants are exact as double by default, but you can specialize them for other floating-point types.

Use these instead of hardcoding 3.14159 or defining your own.

Example

This example uses the pi and sqrt2 constants to calculate the area of a circle and compose other mathematical expressions.

// compile: g++ -std=c++20 -o numbersexample numbersexample.cpp
// run: ./numbersexample
// description: use mathematical constants
 
#include <numbers>
#include <iostream>
#include <cmath>
 
int main() {
    double area = std::numbers::pi * 5.0 * 5.0;
    std::cout << "area of circle (r=5): " << area << "\n";
 
    double result = std::numbers::e * std::numbers::sqrt2;
    std::cout << "e * sqrt(2): " << result << "\n";
 
    return 0;
}
wiki/hpp-numbers.md · Last modified: by 127.0.0.1