c++ - C++ 错误:调用非 constexpr 函数
问题描述
我正在尝试编译以下 C++ 代码(另存为 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;
}
此代码给出以下错误:
example4.cpp:在函数 'constexpr double nth(double, int)' 中:example4.cpp:24:9:错误:调用非 constexpr 函数 '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;
有人可以建议吗?
谢谢你。
解决方案
推荐阅读
- javascript - 更改 div 的颜色
- unity3d - Unity:带有位置视觉提示的小地图凸轮
- android - 错误:程序类型已存在:android.support.v4.app.FragmentTransitionCompat21$1
- composer-php - gcloud composer:网络“network-name”在 x.0.0.0/x 中没有可用的私有 IP 空间来为集群的容器保留 /x 块
- apache-spark - 将 SparseVector 列分解为包含索引和值的行
- azure - 无法运行 Azure Sphere 的闪烁示例
- oberon - Can´t undertand 10th line instruction after inner FOR loop
- netsuite - SuiteScript 2.0 search.create returning empty results
- spring-boot - 有没有办法在 WebMvcTest 中包含一个弹簧组件
- javascript - 在 JavaScript 中构建一个自定义的简单解析器以进行进一步处理