c++ - 将二维数组中的值传递给函数

标签 c++ function multidimensional-array arduino

我有一个包含 255 个四元组的数组,如下所示。

对于 i 的每次迭代,我想将(正确的术语?)每个四元组的前三个值传递给一个函数(下面 getColourDistance 中的三个 ?),以便返回计算结果。

这必须如何在 Arduino 的 C++ 变体中完成?

谢谢!

const int SAMPLES[][4] ={{2223, 1612,  930,  10}, {1855,  814,  530,  20}, {1225,  463,  438,  30}, {1306,  504,  552,  40}, ...};

byte samplesCount = sizeof(SAMPLES) / sizeof(SAMPLES[0]);

for (byte i = 0; i < samplesCount; i++)
{
  tcs.getRawData(&r, &g, &b, &c);
  colourDistance = getColourDistance(r, g, b, ?, ?, ?);
  // do something based on the value of colourDistance
}

int getColourDistance(int sensorR, int sensorG, int sensorB, int sampleR, int sampleG, int sampleB)
{
  return sqrt(pow(sensorR - sampleR, 2) + pow(sensorG - sampleG, 2) + pow(sensorB - sampleB, 2));
}

最佳答案

在这种情况下,数组 SAMPLES 可以被认为是一个二维数组,因此 SAMPLES[0][0] 将给出 SAMPLES 的第一个一维数组的第一个元素,SAMPLES[0][1],将给出 SAMPLES 的第一个一维数组的第二个元素,依此类推,考虑到这个术语,我们可以做到,

#include <iostream>

const int SAMPLES[][4] = {{2223, 1612, 930, 10}, {1855, 814, 530, 20}, {1225, 463, 438, 30}, {1306, 504, 552, 40}, ...};

byte samplesCount = sizeof(SAMPLES) / sizeof(SAMPLES[0]);

for (byte i = 0; i < samplesCount; i++)
{
    //taking values of r,g,b as before    
    a=SAMPLES[i][0];//getting values of r,g,b 
    b=SAMPLES[i][1];//using the knowledge that SAMPLES[i][j]
    c=SAMPLES[i][2];//denotes jth element of ith 1-d array of SAMPLES
    colourDistance = getColourDistance(r, g, b, a, b, c);
}

关于c++ - 将二维数组中的值传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56989254/

相关文章:

c++ - 如何记录 system() 系统调用运行的所有命令

c++ - 函数参数中的 "type name[size]"是什么意思?

c++ - 应该如何编写计算到点的最近距离的 C++ 函数?

postgresql - 您可以将完整的结果集发送到 SQL 函数吗?

nosql - 多维 map 中的 map 维度究竟是什么?

c - 函数无法正确添加二维数组的元素?

ios - 如何在 Swift 中初始化 UIButton 的二维数组?

c++ - 重复调用 - 编码练习

c++ - 为所有 iOS 架构编译 c++ 文件

javascript - 函数标题变量