如何对近似值进行排序?

时间:2013-11-01 21:21:23

标签: c sorting avr

我有一个传感器的数据,它给出了每个时钟周期2种火车(小型和大型)的距离。我想记录测量距离的次数,然后将该值存储在一个数组中,并对该数组进行排序,以查找有多少大型列车和小型列车通过。

例如,我将从火车1的传感器接收到值(500,500,500,500,500,502,523,500,500)。因为火车距离传感器有500毫米的距离。对于火车2(小火车)(500,500,500),因为火车经过传感器3个时钟滴答。

通过了解我得到的传感器脉冲数,我可以确定列车长度。

但我怎样才能正确排序?列车的脉冲不相等

即大火车可能有10个值或11个值。

以下是我存储滴答计数的尝试。哪个不起作用,我无法对此进行排序。

        int i=0;
        int counter=0;
        int train[6];

        if(adc_result > 5)
        {
            counter++;
        }
        train[i] = counter;
        sprintf(result, "%d", train[i]);
        USARTWriteChar(result);
        USARTWriteChar("\r\n");
        i++;

1 个答案:

答案 0 :(得分:1)

这是一个与你的问题一样具体的答案:

#include <windows.h>
#include <ansi_c.h>
#include <stdio.h>
//Assumption: short train is <= 5 clock cycles long  (simulated as value of 30)
//Assumption: long  train is > 10 clock cycles long  (simulated as value of 50)

int randomGenerator(int min, int max);
static uint32_t temper(uint32_t x);
uint32_t lcg64_temper(uint64_t *seed);

int trainType[2]={0,0};; //[0] counts short, [1] counts long

int main(void) 
{

    int i=0, type;

    while(i++ < 1000)
    {
        //simulated train generator
        type = randomGenerator(0,100);//out of a 1000 cycles will hit 30 and 50 a few times.
        //0==no train has occured, do nothing
        //1==short train has occured, increment short train count
        //2==long train  has occured, increment long train count
        switch(type)    {
            case 30://short train
                trainType[0]++;
                break;
            case 50: //long train
                trainType[1]++;
            default: //all other numbers - ignore
                break;
        }
    }   


    return 0;
}

int randomGenerator(int min, int max)
{
    int random=0, trying=0;
    uint64_t lSeed;

    trying = 1;         
    while(trying)
    {

        srand(clock());
        random = (rand()/32767.0)*(max+1);
        ((random >= min)) ? (trying = 0) : (trying = 1);
    }

    return random;
}