Lilla
Lilla

Reputation: 209

Mathematical constant cannot be accessed

#include<numbers>

int main(){
    double x = pi;
}

on C++ 20 throws the error:

error: 'pi' was not declared in this scope

I'm fairly new to C++, what could be wrong?


What was wrong? The compiler wasn't ready for this. I updated it and added -std=c++20 at compile time.

Upvotes: 0

Views: 192

Answers (2)

AziMez
AziMez

Reputation: 2072

This one should work. Tested on GCC 11.11 C++20

#include <iostream>
#include<numbers>

using namespace std::numbers;

int main(){
    double x = pi;
    
    std::cout << "The answer is " << x ;
}

Upvotes: 2

Sam Varshavchik
Sam Varshavchik

Reputation: 118330

The constant pi:

  1. Requires C++20

  2. And is defined in the std::numbers namespace.

You must verify that your compiler implements at least this part of C++20, and provide any required compilation flags for C++20 support, as well as either replace the reference to fully-qualified std::numbers::pi, or add using namespace std::numbers, or maybe a few other aliasing alternatives that you will find explained in your C++ textbook.

Upvotes: 3

Related Questions