奇怪的while循环行为 [英] Strange while loop behavior

查看:52
本文介绍了奇怪的while循环行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我取消注释"//cout<<当前<< endl;"时,感觉如何?在下面的代码中,它有效吗?

How is it that when I uncomment "//cout << current << endl;" in the code below, it works?

#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<<当前<< endl;"之后它会打印:

But after uncommenting the line "//cout << current << endl;" it prints:

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

哪个是正确的,但是如果没有该行,为什么它不起作用?

Which is correct, but why doesn't it work without that line?

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

I use the Android app with ID "com.duy.c.cpp.compiler" version "1.2.4-armeabi-v7a".

推荐答案

这只是我的猜测,但是根据您对 cout<<当前<<endl 您的程序会进行演算,但是唯一会显示在屏幕上的是程序末尾的2计数,因此 power * divizer 的值和flt-epsilon.

This is just my guess but from what I see when you comment cout << current << endl your program does the calculus but the only thing that will print on your screen are the 2 count at the end of your program so the value of power * diviser and the value of flt-epsilon.

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

On the other hand, if you uncomment it your program prints every result of the calculus done in the while loop so that's why it changes a lot what you see (because in the while loop every time you will divide power and add it to current it will print the result and so on until the condition is reached).

我希望我的解释足够清楚^^

I hope that my explanations were clear enough ^^

这篇关于奇怪的while循环行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆