【发布时间】:2013-12-26 21:13:03
【问题描述】:
我希望将常数从度数转换为弧度(在编译时),所以我选择使用 constexpr。但是,我的程序无法编译,因此我尝试通过一些测试来调试问题。这些测试在编译期间继续产生错误。
当涉及许多有效数字时,问题似乎与浮点运算相关。
我尝试了快速的谷歌搜索,并阅读了 Stroustrup 书中的第 10.4 节(常量表达式)。任何帮助将不胜感激。我一定遗漏了一些明显的东西。
测试代码:
void testConstantExpressions() {
constexpr double x0 = 1.0;
constexpr double y0 = 2.0;
constexpr double z0 = 4.0;
constexpr double w0 = x0 / (y0 / z0);
std::cout << w0 << std::endl;
constexpr double x1 = 1.0;
constexpr double y1 = 2.2;
constexpr double z1 = 4.0;
constexpr double w1 = x1 / (y1 / z1);
std::cout << w1 << std::endl;
constexpr double x2 = 1.0;
constexpr double y2 = 4.0;
constexpr double z2 = 2.3;
constexpr double w2 = x2 / (y2 / z2);
std::cout << w2 << std::endl;
}
编译器:
g++ -Wall -c -g -O2 -std=c++11 -frounding-math main.cpp -o main.o
main.cpp: In function ‘void testConstantExpressions()’:
main.cpp:30:32: error: ‘(1.0e+0 / 5.5000000000000004e-1)’ is not a constant expression
constexpr double w1 = x1 / (y1 / z1);
^
main.cpp:36:38: error: ‘(4.0e+0 / 2.2999999999999998e+0)’ is not a constant expression
constexpr double w2 = x2 / (y2 / z2);
^
make: *** [main.o] Error 1
【问题讨论】:
-
在这里用 g++ 编译得很好
-
我在这里没有看到任何无理数。
-
GCC 在使用
-frounding-math时有一些限制。请参阅 this bug 和 this other one。另外,this. -
@Kyle 哎呀,我在为这篇文章选择标题后更改了我的示例。
-
挑剔:没有无理数可以用
double表示。