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

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

问题描述

当我取消注释 "//cout << current << 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 << current << 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"的 Android 应用程序,版本为1.2.4-armeabi-v7a".

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

推荐答案

这只是我的猜测,但根据我在您评论 cout <<当前< 您的程序会进行微积分,但唯一会打印在屏幕上的是程序末尾的 2 计数,因此 power * diviser 的值和 flt- 的值厄普西隆.

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天全站免登陆