这是我第一次用C语言尝试随机数(我想念C#).这是我的代码:
int i, j = 0;
for(i = 0; i <= 10; i++) {
j = rand();
printf("j = %d\n", j);
}
Run Code Online (Sandbox Code Playgroud)
使用此代码,每次运行代码时都会得到相同的序列.但是如果我srand(/*somevalue/*)在for循环之前添加,它会生成不同的随机序列.有谁能解释为什么?
我写了这个函数来获得0 ... 1之间的伪随机浮点数:
float randomFloat()
{
float r = (float)rand()/(float)RAND_MAX;
return r;
}
Run Code Online (Sandbox Code Playgroud)
但是,它总是返回0.563585.无论我运行我的控制台应用程序多少次,都是相同的数字.
编辑:
如果需要,这是我的整个申请:
#include <stdio.h>
#include <stdlib.h>
float randomFloat()
{
float r = (float)rand() / (float)RAND_MAX;
return r;
}
int main(int argc, char *argv[])
{
float x[] = {
0.72, 0.91, 0.46, 0.03, 0.12, 0.96, 0.79, 0.46, 0.66, 0.72, 0.35, -0.16,
-0.04, -0.11, 0.31, 0.00, -0.43, 0.57, -0.47, -0.72, -0.57, -0.25,
0.47, -0.12, -0.58, -0.48, -0.79, -0.42, -0.76, -0.77
};
float y[] = {
0.82, -0.69, 0.80, …Run Code Online (Sandbox Code Playgroud) 我试图在0到3的范围内得到随机数.使用这样的代码:
#include <cstdlib>
int index = rand() % 3;
Run Code Online (Sandbox Code Playgroud)
但总是得到相同的结果:1 1 0 1.
我做错了什么?总是相同的数字.结果应在每次编译后或运行时更改其值?