c++ - For循环间隔

标签 c++ algorithm for-loop

这应该是一个很简单的问题,但我卡住了。

我有一个数组,代表圆的每个角度的特定度量,因此它有 360 个元素。我必须在 +/- 10 度角附近检查这些度量的最小值。这是一个函数,所以角度可以改变。函数是这样的:

double MyClass::FindMin(int angle) {
  lower_limit = x-10;
  upper_limit = x+10;
  for(int i=lower_limit; i<upper_limit; i++) {
    //Find the minimum
  }
  return minimum;
}

如果我的角度值为 300,for 循环将是这样的:

for(int i=290; i<310; i++)

当角度在 360 度左右时,问题就来了:

for(int i=355; i<365; i++)

这显然行不通,因为数组有 360 个值。

有什么优雅的方法可以解决这个问题吗?

最佳答案

您可以使用取模运算符计算一个正确换行的新索引 j:

double findmin(int angle) {
  int lower_limit = angle + 350;
  int upper_limit = angle + 370;
  double minimum = 0.0;

  for(int i = lower_limit; i < upper_limit; i++) {
    // compute a new index j that wraps using the modulus operator
    int j = i % 360;

    // find minimum using j 
  }

  return minimum;
}

编辑:根据@EdHeal 在评论中的反馈进行了修改。

关于c++ - For循环间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49576224/

相关文章:

algorithm - 是否有任何公式可以将 [0..πR²] 范围内的 int 映射到半径 R 的圆内的 (x,y) 坐标?

c - 在 C 中实现求和公式

c# - 获取数组中的枚举元素

javascript - 如何在 node.js 中的 for 循环中编写回调函数

c++ - 如何在 qt 中为 QAbstractListModel 创建 CurrentIndexChanged 信号?

c++ - QWebSocket Hello World示例

algorithm - 数组中正数和负数交替

python - 基于 YAML 数据的条件 Python for 循环

c++ - 显式特化,C++

c++ - 指向指针数组的指针理解问题