c++ 如何从数组中计算索引[已关闭]

k75qkfdt  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(1573)

**已关闭。**此问题需要debugging details。它目前不接受回答。

编辑问题以包括desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将有助于其他人回答这个问题。
9天前关闭。
Improve this question
我想计算哪个索引保存了包含位图数据的向量中的X/Y坐标数据。

int receiveBitmapCoordinateIndex(int x, int y, int bmp_width, int bmp_height) {
    int final = 0;

    // Y
    final += bmp_width * (bmp_height - y);

    // X
    final += x - 1;

    return final;
    //((((bmp_height)-(y)) * bmp_width) + x);
}
int main()
{   
    std::cout <<"Should be: 249 999 func:" << receiveBitmapCoordinateIndex(1, 1, 500, 500) << "\n";
    std::cout << "Should be: 249 998 func:" << receiveBitmapCoordinateIndex(2, 1, 500, 500) << "\n";
    std::cout << "Should be: 0 func: " << receiveBitmapCoordinateIndex(500, 500, 500, 500) << "\n";
system("pause");
}

字符串
向量的大小为500 * 500 = 250 000,但第一个索引为0,最后一个索引为249 999。
位图数据是颠倒的,这意味着X:1 Y:1将是249 999,我的数学做错了什么?
我试着改变周围的数学,但我似乎不能让它工作,老实说,不知道我做错了什么。

8yoxcaq7

8yoxcaq71#

对于位图数据,调整函数以从bmp_height + 1中减去y,并保持x不变。
Pixel (1,1)对应数组的末尾,(width,height)对应数组的开始。

int receiveBitmapCoordinateIndex(int x, int y, int bmp_width, int bmp_height) {
    int final = 0;

    // Y
    //final += bmp_width * (bmp_height - y);
    final += bmp_width * (bmp_height + 1 - y); //<---- here

    // X
    //final += x - 1;
    final += x; //<---- here

    // Subtracting one because array indexing starts from 0
    final -= 1;

    return final;
}

int main()
{   
    std::cout << "Should be: 249 999 func: " << receiveBitmapCoordinateIndex(1, 1, 500, 500) << "\n";
    std::cout << "Should be: 249 998 func: " << receiveBitmapCoordinateIndex(2, 1, 500, 500) << "\n";
    std::cout << "Should be: 0 func: " << receiveBitmapCoordinateIndex(500, 500, 500, 500) << "\n";
    system("pause");
}

字符串

相关问题

微信公众号