我想生成双随机值。好的,我输入:
random_value = ((double)rand() / (double)RAND_MAX);
用 printf 做一点检查:
printf("rand: %f ", random_value);
很好,来自 <0,1> 的值。然后在 printf 之后我写道:
random_value *= range; // range have values from <0.05, 0.5>
printf("random_value: %f, range:%f\n", random_value, range);
现在它对我来说开始变得神奇了。FIRST printf (printf("rand: %f ", random_value);) 开始只给我从 <0.8, 1> 的值,其中大多数值接近 ~0.99。当我删除这一行时:
random_value *= range;
一切恢复正常。为什么会这样?
代码:
double random_value;
double range;
srand(time(NULL));
(...)
random_value = ((double)rand() / (double)RAND_MAX);
printf("rand: %f ", random_value);
random_value*=range;
printf("random_value: %f, range:%f\n", random_value, range);
编译命令:
gcc -lm ant.c -o ant -O0
海湾合作委员会:
gcc (GCC) 4.7.2
系统:
Linux 3.6.10-1-ARCH #1 SMP PREEMPT Tue Dec 11 09:40:17 CET 2012 x86_64 GNU/Linux
没有 random_value *= range 的输出;
rand: 0.534583 random_value: 0.534583, range:0.156963
rand: 0.909061 random_value: 0.909061, range:0.156963
rand: 0.144450 random_value: 0.144450, range:0.156963
rand: 0.235249 random_value: 0.235249, range:0.156963
rand: 0.978194 random_value: 0.978194, range:0.156963
random_value *= range 的输出;
rand: 0.965320 random_value: 0.570025, range:0.590504
rand: 0.991456 random_value: 0.155622, range:0.156963
rand: 0.957783 random_value: 0.392337, range:0.409631
rand: 0.970194 random_value: 0.122562, range:0.126327
rand: 0.980422 random_value: 0.132694, range:0.135344