如果是一个例子,我设置的值是:
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/