可以for循环有双重值作为索引在C和C + +? [英] can the for loop have double value as index in c and c++?

查看:326
本文介绍了可以for循环有双重值作为索引在C和C + +?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  for(double d = 2.0; d< 3.1; d + = 0.1)


解决方案

C99和C ++。只要 d 没有在循环内部乱作一团,它就是确定性的(应该结束)。



虽然循环确实会终止,但究竟会发生多少次循环迭代还不清楚。在第12次迭代中, d 的值将从理论上递增到 3.1 ,但它可能是 3.099999 .. (或类似的东西),也可能是 3.1000 ... 01 (或类似的东西)。所以循环是否会做11或12次迭代是不清楚的。你不想依赖于浮点的精确匹配。


Is it legal to have the following for loops in c and c++:

for(double d=2.0; d<3.1; d+=0.1)

解决方案

It is legal syntax for C99 and C++. And it is deterministic (should end) as long as d isn't improperly fiddled with inside the loop.

Although the loop will indeed terminate, it's unclear exactly how many loop iterations will occur. On the 12th iteration, the value of d will be incremented to, theoretically, 3.1, but it may be 3.099999.. (or something similar) or it could be 3.1000...01 (or something similar) due to rounding. So whether the loop will do 11 or 12 iterations is unclear. You don't want to rely on exact matches in floating point.

这篇关于可以for循环有双重值作为索引在C和C + +?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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