Find Region and Calculate Region Average

Find Region and Calculate Region Average

若有一數列為

1.0,
0.0,
0.0,
4.2,
3.1,
4.8,
0.0,
7.1,
0.0,
1.0,
2.0,
0.0,
0.0,
1.5,
0.0,
1,1

欲尋找此數列 不為零的群組,並計算此群組的平均

1   1.0,    avg = 1.0
    0.0,
    0.0,
2   4.2,
2   3.1,    avg = (4.2+3.1+4.8)/3
2   4.8,
    0.0,
3   7.1,    avg = 7.1
    0.0,
4   1.0,    avg = (1.0 + 2.0) /2
4   2.0,
    0.0,
    0.0,
5   1.5,    avg = 1.5
    0.0,
6   1,1     avg = 1.1


 
void main()
{
    int i = 0, preFlag = 0, curFlag = 0;
    float fsum = 0.0f;
    int n = 0, nReg = 0;
    float af[16] = {
        1.0,
        0.0,
        0.0,
        4.2,
        3.1,
        4.8,
        0.0,
        7.1,
        0.0,
        1.0,
        2.0,
        0.0,
        0.0,
        1.5,
        0.0,
        1.1
    };
   
    for (i = 0 ; i <16; i++)
    {
        curFlag = (af[i] == 0.0 ? 0 : 1);
        if (preFlag == 0 && curFlag == 1)
        {   
            nReg++;
        }
       
        if (curFlag == 1)
        {
            fsum += af[i];
            n++;
            printf("reg %d : %.2f\n", nReg, af[i]);
        }
 
        if (preFlag == 1 && curFlag == 0 || (curFlag == 1 && (i == 15)))
        {
            printf("avg:%.2f\n", fsum/n);
            fsum = 0;
            n = 0;
        }
       
        preFlag = curFlag; 
    }
 
   
    printf("Total Regions:%d\n", nReg);
}

輸出

reg 1 : 1.00
avg:1.00
reg 2 : 4.20
reg 2 : 3.10
reg 2 : 4.80
avg:4.03
reg 3 : 7.10
avg:7.10
reg 4 : 1.00
reg 4 : 2.00
avg:1.50
reg 5 : 1.50
avg:1.50
reg 6 : 1.10
avg:1.10