如何解决 for 循环中的差一问题

How to fix off-by-one issue in for-loop

我从文件中读取了一些变量值,然后执行 运行 总计算。我的目标是找出我总共完成了多少次计算。我可以通过在最后从我的计数器中减去 1 来得到正确的数字,但我不想通过改变我的条件来更好地适应它来做到这一点。我意识到我没有在我的情况下使用计数器,这是个问题吗?

输入示例:a=10, b=5, t=70

如有任何帮助,我们将不胜感激。尝试将条件更改为 sum < t 但它似乎过度计算了 70。

//Reads and calculates a, b and t, and outputs number of dishes to output.txt
while (inFile >> a)
{       
inFile >> b >> t;

for (counter = 0; sum <= t ; counter++)
{
sum += a + (counter * b);
}
outFile << " " << a << "\t\t" << b << "\t\t" << t << "\t\t" << counter -1 << endl; //Output iteration results

//Reset total before next iteration
sum = 0;
}

像这样。它使用一个临时变量,它是 sum 的下一个值,如果该值太大则中止循环。

for (counter = 0; ; ++counter)
{
    int temp = sum + a + (counter * b);
    if (temp > t)
        break; // too big quit the loop
    sum = temp;
}

现在 countersum 应该在循环结束时具有正确的值。