【问题标题】:Strange while loop behavior奇怪的while循环行为
【发布时间】:2020-05-21 15:38:33
【问题描述】:

当我取消注释“//cout

#include <iostream>
#include <float.h>

using namespace std;

int main()
{
  char divider = 2;
  float power = 1;
  float number = 1;
  float current = number + power;
  cout.precision(1024);
  // Divide until rounded off
  while(current != number)
  {
    power /= divider;
    current = number + power;
    //cout << current << endl;
  }

  cout << power * divider << endl;
  cout << FLT_EPSILON << endl;
}

上面的代码打印:

1.40129846432481707092372958328991613128026194187651577175706828388979108268586060148663818836212158203125e-45
1.1920928955078125e-07

但在取消注释“//cout

1.5
1.25
1.125
1.0625
1.03125
1.015625
1.0078125
1.00390625
1.001953125
1.0009765625
1.00048828125
1.000244140625
1.0001220703125
1.00006103515625
1.000030517578125
1.0000152587890625
1.00000762939453125
1.000003814697265625
1.0000019073486328125
1.00000095367431640625
1.000000476837158203125
1.0000002384185791015625
1.00000011920928955078125
1
1.1920928955078125e-07
1.1920928955078125e-07

哪个是正确的,但为什么没有那行就不行?

我使用 ID 为“com.duy.c.cpp.compiler”版本“1.2.4-armeabi-v7a”的 Android 应用。

【问题讨论】:

  • cout.precision(1024) 很多 并且已经足够好了)。
  • 您确定它会打印您在评论时给出的输出吗?因为我尝试运行它并得到了不同的输出
  • 我运行了你的代码,它给出了不同的输出 1.1920928955078125e-07 1.1920928955078125e-07
  • 注释版本似乎也可以正常工作:onlinegdb.com/SkbiFmVo8
  • 似乎 OP 使用 -ffast-math 标志 Demo(gcc 给出 0 而 clang 给出 espilon)。

标签: android c++ while-loop


【解决方案1】:

这只是我的猜测,但根据我在您评论 cout &lt;&lt; current &lt;&lt; endl 时看到的情况,您的程序会进行微积分,但唯一会打印在屏幕上的是程序末尾的 2 计数,因此 @987654322 的值@ 和 flt-epsilon 的值。

另一方面,如果您取消注释,您的程序会打印在 while 循环中完成的每个演算结果,这就是为什么它会改变您所看到的很多内容(因为在 while 循环中,每次您将分权并添加它到当前,它将打印结果,依此类推,直到达到条件)。

希望我的解释够清楚^^

【讨论】:

  • 我相信 OP 指的是倒数第二行,它应该不受注释行的影响——但实际上它是不可重现的。
【解决方案2】:

感谢 Jarod42,看来您是对的。这是因为 -ffast-math。

添加解决

#pragma GCC optimize ("no-fast-math")

到代码。

无论如何,有人可以解释一下优化数学如何导致条件成立吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多