I am trying to compile the following C++ code (saved as example4.cpp)
#include <iostream>
using namespace std;
constexpr double nth(double x, int n);//initialization
int main()
{
double x=2;
int n=5;
nth(x,n);//Function call
return 0;
}
constexpr double nth(double x, int n) // function definition
{
double res = 1;
int i = 0;
while (i<n) { // while-loop: do while the condition is true
res*=x;
++i;
}
cout << res;
cout << endl;
return res;
}
This code is giving the following error:
example4.cpp: In function ‘constexpr double nth(double, int)’: example4.cpp:24:9: error: call to non-constexpr function ‘std::basic_ostream<_CharT, _Traits>::__ostream_type& std::basic_ostream<_CharT, _Traits>::operator<<(double) [with _CharT = char; _Traits = std::char_traits; std::basic_ostream<_CharT, _Traits>::__ostream_type = std::basic_ostream]’ cout << res;
Can anyone please suggest?
Thank you.
nth(x,n);
tocout << nth(x, n) << endl;
– user4581301