随机数生成正确,但当我将其存储到数组时,有时它接受垃圾值
void main()
{
int x = 0, y = 0, i = 0;
srand(time(NULL));
int r = rand();
/*Generating Random Number in Floating Point. For calculating Dimension of Rectangle*/
srand((unsigned int)time(NULL));
float a = 5.0, s[20], sum = 0, x_rand;
for (i=0; i<20; i++)
{
x_rand = (((float)rand()/(float)(RAND_MAX)) * a) + sum;
sum += 1.53;
//s[i] = x_rand;
if(i != 0)
{
if(x_rand>s[i-1])
s[i] = x_rand;
}
else
{
s[i] = x_rand;
}
printf("%f\n", x_rand);
}
printf("--------------------------\n");
for(i =0 ; i<20; i++)
printf("%.5f\n",s[i]);
}
最佳答案
在您的代码中,如果 i
为 0
,则 s[i]
保持未初始化状态。
使用更好的缩进。您的代码本质上与
相同 if(i != 0)
{
if(x_rand>s[i-1])
{
s[i] = x_rand;
}
else
{
s[i] = x_rand;
}
}
//where is else????
相关,引用 C11
,第 §6.8.4.1 章
An
else
is associated with the lexically nearest precedingif
that is allowed by the syntax.
关于c - 尝试将随机生成的 float 存储在数组中。但无法理解为什么数组采用垃圾值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40286510/