本文介绍了constexpr:浮点表示错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我希望将常数从度转换为弧度(在编译时),因此我选择使用constexpr。但是,我的程序无法编译,因此我尝试通过一些测试来调试问题。这些测试在编译过程中继续产生错误。

I was hoping to convert a constant from degrees to radians (at compile time), so I opted to use a constexpr. However, my program would not compile and so I tried to debug the problem with a few tests. These tests continue to produce errors during compilation.

当涉及到许多有效数字时,出现的问题 与浮点算术相关。

The problem appears to be correlated with floating point arithmetic when many significant digits are involved.

我尝试了快速的Google搜索,并且阅读了Stroustrup的书中的10.4节(常量表达式)。任何帮助将不胜感激。我必须缺少明显的东西。

I tried a quick google search, and I read section 10.4 (Constant Expressions) in Stroustrup's book. Any help would be greatly appreciated. I must be missing something obvious.

测试代码:

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


推荐答案

这是因为您指定了-frounding-math。您告诉编译器您可能会在运行时更改舍入模式,因此它不能在编译时舍入。你真的是故意的吗?

It's because you specified -frounding-math. You told the compiler you might change rounding mode at runtime, so it can't round at compile time. Did you really mean to?

这篇关于constexpr:浮点表示错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 02:37