如何用C语言进行减量?

时间:2017-01-31 16:49:15

标签: c

如果是一个例子,我设置了一个值:

a = 50 

如何减少总是减少2?一个例子:

48
46
44
42
40

因此返回结果,我可以用作变量。在下面的例子中,这种方法是随机获得温度。但是我希望它能减少,这样我就可以调用这个get温度方法,以便循环。

/* Retrieves current temperature. */
static int32_t get_temperature_sample(void)
{
    /* For the sake of example, random data is used */
    return rand() % 10 + 25;
}

/* Periodically called by Kaa SDK. */
static void example_callback(void *context)
{
    time_t current_time = time(NULL);

    /* Respect sample period */
    if (difftime(current_time, last_sample_time) >= sample_period) {
        int32_t temperature = get_temperature_sample();

        printf("Sampled temperature: %i\n", temperature);
        last_sample_time = current_time;

        kaa_user_log_record_t *log_record = kaa_logging_data_collection_create();
        log_record->temperature = temperature;

        kaa_logging_add_record(kaa_client_get_context(context)->log_collector, log_record, NULL);
    }
}

就像上面的代码一样,如果我说的是我的温度。我不希望它是随机的,因为你可以看到它使用随机。我想为我的温度设置一个值并像常量一样减小,直到它在我的打印函数中达到0。

printf("Sampled temperature: %i\n", temperature);
        last_sample_time = current_time;

2 个答案:

答案 0 :(得分:0)

尝试这样的事情

static void get_temperature_sample(int *previous_temp)
{
    *previous_temp -= 2; // This decrements the value and 
                         // don't need a return value, because
                         // you are passing a pointer to
                         // the variable and hence modifying
                         // it's value directly
}

当你调用函数

int32_t temperature = 50;      // Initial temperature
get_temperature_sample(&temperature);

根据您跟踪温度的方式,您需要在其中的某处添加一段时间。但是每当你调用函数时,这都会减小临时值。

答案 1 :(得分:0)

要递减a,请尝试使用

 a -=2;

它会帮助你..