c - C语言中如何实现自减?

标签 c

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

a = 50 

如何进行减量以使 a 始终减少 2 ?一个例子:

48
46
44
42
40

其中返回结果,我可以用作变量。以下面的情况为例,该方法是随机获取温度。但我希望它减少,这样我就可以调用这个获取温度的方法,甚至低于它的循环。

/* 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;

最佳答案

尝试这样的事情

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);

您需要在其中的某个位置添加一段时间,具体取决于您跟踪温度的方式。但是,每当您调用该函数时,这都会减少临时值。

关于c - C语言中如何实现自减?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41962996/

相关文章:

c - C 遍历链表,陷入循环

c - time.h 库不工作

c - 如何在while循环中处理多个相似条件?

无法获取要显示的三角形面积

c - 用完 ram 声明全局二维数组问题

c++ - libjpeg:复制整个数据

c - 两个参数 c

c - 如何在 NetSim 中编写自己的代码?

c - MPI_Allgather 的负缩放

c - 将c中的argv解析为unix中的命令