计算1维c ++上的2d数组的平均值

问题描述 投票:-1回答:1

我有一个2d数组[pixels = 100] [sensors = 50](在data.cpp文件中提供)我需要每个像素的传感器给出的平均值。结果应存储在E [100] / 50中,其中包含先前计算的平均值。

**编辑:问题解决了!!这是在数组类型short一旦我改变了我得到了正确的价值观!感谢所有花时间回答我的问题的人也谢谢你介绍我containers **

这是我的代码:

#include <iostream>

#include "const.h"
#include "data.h"
#include "SortEngine.h"
#include "test.h"
#include "fonction.h"
//example of how data is defined data 2darray[pixels = 10][sensors = 3]






      /* unsigned short 2darray{{ 10025 , 10192 , 10028 , 10129 , 10199 , 9843 , 9823 , 9857 , 9996 , 9873},
    {10081 , 10122 , 9853 , 10060 , 10027 , 10165 , 10154 , 9853 , 9877, 9816},
    {9845 , 9876 , 9954 , 9836 , 9876 , 10035 , 10094 , 9946 , 10195 

, 10080}} */


    void moyenne(unsigned short average[pixels])
{
    unsigned short transtab[pixels][sensors];
    unsigned short E[pixels];
    unsigned int i,k, count;

    Acquisition(0, transtab);// function to get the data from data.cpp


    for(i=0; i<pixels; i++)
    {
        E[i] = 0;
        average[i] = 0;
        count = 0;

        for(k=0; k<sensors; k++)
        {
            E[i] = E[i] + transtab[i][k];

            count++;
        }
        if(count != 0){
        average[i] = E[i]/count;
        }
        cout << average[i] << endl;

        }

    }

因为我没有看到问题所以我已经坚持了2天。任何帮助,将不胜感激。谢谢。

注意:平均值[0] = 10029的预期值,而我用我的代码得到的值:853(通常,代码应该对transtab [0] [k](其中k <50)的所有元素求和,其中平均值为这个数量总和)

c++
1个回答
0
投票

问题似乎是你在计算空数组值。您的代码计数始终等于传感器。您必须首先检查transtab [i] [k]!= 0

for(k=0; k<sensors; k++)
{
  if (transtab[i][k] != 0) {
    E[i] = E[i] + transtab[i][k];
    count++;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.