模块化操作(%)提供错误的输出 [英] Modular opertation (%) provides false output

查看:57
本文介绍了模块化操作(%)提供错误的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用函数 getNextIdx ,我想为数组接收一个新索引,该索引取决于当前索引和该索引处的数组的值.

With a function, getNextIdx, I want to receive a new index for an array that depends on the current index and the value of the array at that index.

我希望函数通过将当前索引与该索引处的数组值相加,以数组的大小为模,来返回新索引.

I want the function to return the new index by summing the current index with the value of the array at that index, modular to the array size.

#include<vector> 
using namespace std;

int getNextIdx(int currentIdx, vector<int> array) {
    int jump = array[currentIdx];
    int nextIdx = (currentIdx + jump) % array.size();
    
    return (nextIdx >= 0) ? nextIdx : nextIdx + array.size();
}
int main() {
    vector<int> test = {2, 3, 1, -4, -4, 2};
    int nextIdx = getNextIdx(3, test);    
} 

示例:如果当前索引为3(第4个元素),并且数组中第4个元素的值为-4,并且数组的大小为6,则该函数应返回5.

Example: If the current index is 3 (4th element), and the value of the 4th element in the array is -4, and the size of the array is 6, then the function should return 5.

问题是我的程序在上面的示例中返回3.

The problem is that my program returns 3 in the above example.

推荐答案

模数运算符四舍五入为零(即使对于负数也是如此).您的数学期望模数朝负或正无穷大取整.参见具有负数的模运算

The modulus operator rounds towards zero (even for negative numbers). Your math expects modulus to round towards negative or positive infinity. See Modulo operation with negative numbers

int getNextIdx(int currentIdx, vector<int> array){
  int jump = array[currentIdx];
  int nextIdx = currentIdx + jump;
  if (nextIdx < 0)
    nextIdx += array.size();
  if (nextIdx >= array.size())
    nextIdx -= array.size();
  return nextIdx;
}

这篇关于模块化操作(%)提供错误的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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