C - 随机值 +/- 前一个值

C - Random value +/- from previous value

我试图用 C 语言编写一些代码来模拟与之前值相比 +/- 4 的温度波动,但是我在任一方向上都有一些疯狂的跳跃。

该程序是多线程的,但是,即使单独测试也会产生相同的错误结果。

我尝试了几种代码变体,认为这与代码的计算方式有关,但我的错误最终都是一样的。我的代码如下:

int main(){
    srand(1); //Just for testing and predictability of outcome
    //short int temp = 20 + rand() / (RAND_MAX / 30 - 20 + 1) + 1; Initially I was initialising it at a random value between 20-30, but chose 20 for testing purposes
    short int temp = 20;
    short int new_temp, last_temp, new_min, new_max;
    last_temp = temp;
    for(int i = 0; i < 20; i++){
        //last_temp = temp; At first I believed it was because last_temp wasn't being reassigned, however, this doesn't impact the end result
        new_min = last_temp - 4;
        new_max = last_temp + 4;
        //new_temp = (last_temp-4) + rand() / (RAND_MAX / (last_temp + 4) - (last_temp - 4) + 1) + 1; I Also thought this broke because they last_temp was being changed with the prior math in the equations. Still no impact
        new_temp = new_min + rand() / (RAND_MAX / new_max - new_min + 1) + 1;

        printf("Temperature is %d\n", new_temp);
    }
    
    return 0;
}

产生这样的结果。

Temperature is 37
Temperature is 26
Temperature is 35
Temperature is 36
Temperature is 38

如您所见,第一个温度读数应该在 16-24 的范围内,但是它增加了 17 到 37,我不明白为什么。任何见解将不胜感激。或者,谁能为我提供一种无需使用大量嵌入式 if 语句即可模拟随机 +/- 的简洁方法?

此代码中有 2 个问题:

  1. rand() 用法
  2. last_temp 值不会在每次迭代中更新

rand 用法

rand() returns 介于 0 和 RAND_MAX 之间的值。你想把这个值限制在[0,8],加到new_min,这样new_temp就限制在[last_temp-4,last_temp+4], ie [new_min,new_min+8].

为此,您可以使用 % 运算符。通过执行 rand() % 9,您将随机值限制在 0 到 8 之间。因此,new_temp 值应为:new_temp = new_min + rand() % 9.

last_temp更新

您需要像这样分配 new_temp 值后更新 last_temp 值:

new_temp = new_min + rand() % 9;
last_temp = new_temp;

所以,你的 for 循环最后应该是这样的:

for(int i = 0; i < 20; i++){
    new_min = last_temp - 4;
    new_max = last_temp + 4;
    new_temp = new_min + rand() % 9;
    last_temp = new_temp;

    printf("Temperature is %d\n", new_temp);
}

代码可以简化为:

int main() {
    srand(1); //Just for testing and predictability of outcome
    short int temp = 20; //or 20 + rand()%11 for values in [20,30] range
    for(int i = 0; i < 20; i++) {
        temp += -4 + rand() % 9;
        printf("Temperature is %hd\n", temp);
    }
    return 0;
}

结果为:

Temperature is 23
Temperature is 25
Temperature is 22
Temperature is 21
Temperature is 18
Temperature is 21
Temperature is 19
Temperature is 19
Temperature is 16
Temperature is 17
Temperature is 15
Temperature is 14
Temperature is 12
Temperature is 11
Temperature is 10
Temperature is 12
Temperature is 12
Temperature is 10
Temperature is 10
Temperature is 6