我已经做了一段时间并且遇到了很多麻烦.我想生成一个从-1到1的随机值进行计算.我不能使用%运算符,因为它仅适用于整数.我也试过用,fmod()
但我也遇到了困难.
我试图使用的是......
double random_value;
random_value = fmod((double) rand(),2) + (-1);
Run Code Online (Sandbox Code Playgroud)
看起来它似乎不正确.我也试着用时间播种srand,但我认为我在那里做错了,因为它一直在抛出这个错误:
"error: expected declaration specifiers or '...' before time"
Run Code Online (Sandbox Code Playgroud)
码:
srand((unsigned) time(&t));
Run Code Online (Sandbox Code Playgroud)
任何有关这些问题的帮助都会受到赞赏.
这将为随机数生成器播种,并在-1.0到1.0的范围内给出一个double
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
double random_value;
srand ( time ( NULL));
random_value = (double)rand()/RAND_MAX*2.0-1.0;//float in range -1 to 1
printf ( "%f\n", random_value);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
您可以rand
像下面这样随时间播种(一次调用之前):
#include <time.h>
// ...
srand (time ( NULL));
Run Code Online (Sandbox Code Playgroud)
使用此功能,您可以根据需要设置最小值/最大值。
#include <stdio.h>
#include <stdlib.h>
/* generate a random floating point number from min to max */
double randfrom(double min, double max)
{
double range = (max - min);
double div = RAND_MAX / range;
return min + (rand() / div);
}
Run Code Online (Sandbox Code Playgroud)
然后,您将这样称呼它:
double myRand = randfrom(-1.0, 1.0);
Run Code Online (Sandbox Code Playgroud)
但是请注意,这很可能不会涵盖的所有精度范围double
。甚至不考虑指数,IEEE-754的double包含52位有效数字(即非指数部分)。由于rand
一个回报int
之间0
和RAND_MAX
,的最大可能值RAND_MAX
是INT_MAX
。在许多(大多数?)平台上,int
都是32位,覆盖范围INT_MAX
是0x7fffffff
31位。
归档时间: |
|
查看次数: |
23805 次 |
最近记录: |