使用“双”作为循环中的计数器变量 [英] Using "double" as counter variables in loops

查看:229
本文介绍了使用“双”作为循环中的计数器变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一本我正在阅读的书中,有这样的摘录:

lockquote

你也可以使用浮点数
值作为循环计数器。
















$ (0.3),b(2.5);
(double x = 0.0;x≤2.0; x + = 0.25)
cout< \\\
\tx =<< x<< \ta * x + b =<< a * x + b;

这个代码片段计算
的值code> a * x + x
0.0 > 2.0 ,步数为
0.25 ;但是,在
a循环中使用浮点计数器时,需要注意
。许多十进制值不能完全以二进制
浮点形式表示,因此可以用累积值建立差异

这意味着你不应该编写一个
for循环,这样结束
循环取决于一个浮点循环
计数器达到一个精确的值。对于
例子,以下设计不当的
循环永远不会结束:

$ p $ for(double x = 0.0 ; x!= 1.0; x + = 0.2)
cout< X;

这个循环的意图是
输出 x ,因为它从 0.0 到 1.0 ;但是, 0.2
没有确切的表达式作为
二进制浮点值,因此 x 永远不会是 1
因此,第二个循环控制
表达式总是为false,并且
循环将无限期地继续。



<有人可以解释第一个代码块是如何运行的,而第二个代码块是不是运行的?

解决方案

第一个最终会终止,即使 x 没有达到 2.0 ,因为它最终会比<2.0>更大,因此爆发。



第二个必须使 x 命中正好 1.0为了打破。



不幸的是,第一个例子使用了一个0.25的步骤,这个步骤在二进制浮点中是精确表示的 - 两个例子都使用0.2作为步长。 (0.2在二进制浮点上不能完全表示。)


In a book I am currently reading, there is this excerpt:

You can also use a floating-point value as a loop counter. Here's an example of a for loop with this kind of counter:

double a(0.3), b(2.5);
for(double x = 0.0; x <= 2.0; x += 0.25)
    cout << "\n\tx = " << x << "\ta*x + b = " << a*x + b;

This code fragment calculates the value of a*x+b for values of x from 0.0 to 2.0, in steps of 0.25; however, you need to take care when using a floating-point counter in a loop. Many decimal values cannot be represented exactly in binary floating-point form, so discrepancies can build up with cumulative values. This means that you should not code a for loop such that ending the loop depends on a floating-point loop counter reaching a precise value. For example, the following poorly-designed loop never ends:

for(double x = 0.0 ; x != 1.0 ; x += 0.2)
    cout << x;

The intention with this loop is to output the value of x as it varies from 0.0 to 1.0; however, 0.2 has no exact representation as a binary floating-point value, so the value of x is never exactly 1. Thus, the second loop control expression is always false, and the loop continues indefinitely.

Can someone please explain how the first code block runs while the second doesn't?

解决方案

The first one will eventually terminate, even if x doesn't reach exactly 2.0... because it'll end up being greater than 2.0, and thus break out.

The second one would have to make x hit exactly 1.0 in order to break.

It's unfortunate that the first example uses a step of 0.25, which is exactly representable in binary floating point - it would have been smarter to make both examples use 0.2 as the step size. (0.2 isn't exactly representable in binary floating point.)

这篇关于使用“双”作为循环中的计数器变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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