如何正确地迭代一遍 [英] How to properly iterate over a double

查看:95
本文介绍了如何正确地迭代一遍的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在像这样遍历 t

double dt = 0.1, t;
double tmax = 100;
for (t = 0; t <= tmax; t += dt) { /*do something*/ }

如果 dt 为0.1,则此处一切正常,并且步骤 t = 100 。但是,如果我减少步骤,例如 dt = 0.001 ,则不会执行最后一步。

If dt is 0.1, as here, everything works as it should and the step is executed for t = 100. But if I decrease the step, for example dt = 0.001, the last step is not executed.

应该如何我可以正确地对双精度进行迭代吗?

How should I properly iterate over doubles?

推荐答案

对整数进行迭代,并使用开始步骤公式来获取每个double值。

Iterate over an integer and use a start-step formula to get each double value.

double dt = 0.1, t;
double tmax = 100;
int i, n = (int)(tmax / dt); // n: check your rounding or specify explicitly.
for (i = 0; i <= n; i++) { t = 0/*start*/ + dt * i; /*do something*/ }

这篇关于如何正确地迭代一遍的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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