首页 > 解决方案 > 减少在 C 中按倍数计算所需的计算量

问题描述

x我试图用uint8_tc 数组中的倍数来计数。这样,每当倍数x溢出 256 限制时,它就会在下一个类别中增加,类似于时钟的指针或二进制计数。如果x是 80,一个例子可能是:

(0,   0,  0)  ->  0
(80,  0,  0)  ->  1
(160, 0,  0)  ->  2
(240, 0,  0)  ->  3
(0,   80, 0)  ->  4
...

到目前为止,我已经能够使用这些方程组来实现它:

uint16_t get_max(uint8_t bound){
  return (255+bound)/bound;
}

static void bind(uint32_t val, uint8_t bound, uint8_t rgb[3]){
  uint16_t max = bound*get_max(bound);

  rgb[0] = (val*bound)%max;
  rgb[1] = (((val*bound)/max)*bound)%max;
  rgb[2] = (((((val*bound)/max)*bound)/max)*bound)%max;
}

然而,我觉得对于这样一个简单的任务来说,这些方程中的很多似乎是不必要的。有没有更有效的方法来实现我忽略的这一点?

标签: arraysc

解决方案


看来您可能正在寻找类似以下的内容。如果没有,您需要澄清任务。

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>


enum { NCounters = 3 }; //  Number of elements in the counter array.


/*  Add increment to the given counter.  If it does not overflow, return 0.
    If it overflows, reset the counter to 0 and report a carry.
*/
int AddOne(uint8_t increment, uint8_t counters[1])
{
    unsigned a = counters[0] + increment;
    if (256 <= a)
    {
        counters[0] = 0;
        return 1;
    }
    else
    {
        counters[0] = a;
        return 0;
    }
}


/*  Add increment to the counters, starting with the lowest counter and
    proceeding to higher counters as long as there is a carry.  If it does not
    overflow out of all the counters, return 0.  If it overflows, report a
    carry.
*/
int Add(uint8_t increment, uint8_t counters[NCounters])
{
    for (size_t i = 0; i < NCounters; ++i)
        if (!AddOne(increment, &counters[i]))
            return 0;
    return 1;
}


int main(void)
{
    //  Initialize counters to zero.
    uint8_t counters[NCounters] = { 0 };

    /*  Repeatedly print the counters and add the increment until the add
        reports a carry out of the counters.
    */
    do
    {
        printf("(%3d", counters[0]);
        for (size_t i = 1; i < NCounters; ++i)
            printf(", %3d", counters[i]);
        printf(")\n");
    } while (!Add(80, counters));
}

推荐阅读