gcc有双兰特的问题吗?

时间:2012-12-22 21:04:17

标签: c gcc random double

我想生成双随机值。好的,我输入了:

random_value = ((double)rand() / (double)RAND_MAX);

很少检查printf:

printf("rand: %f ", random_value);

很棒,价值来自< 0,1>。然后AFTER 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);)开始仅给出来自&lt; 0.8,1&gt;的值,其中大多数值接近~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 (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的输出* =范围;

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输出* =范围;

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

0 个答案:

没有答案