gpt4 book ai didi

c - rand() 不返回随机值

转载 作者:太空狗 更新时间:2023-10-29 11:23:51 26 4
gpt4 key购买 nike

生成随机厄密矩阵的小代码hermitian matrix .

我在每次调用 rand() 之前调用了 srand()。但输出仍然没有随机性。

我已经使用 c99 的复杂数据类型功能创建了厄尔米特矩阵。我不确定我哪里错了:(

#include <stdio.h>
#include <math.h>
#include <complex.h>
#include <stdlib.h>
#include <time.h>

#define MATSIZE 5
#define RAND_RANGE 100

double complex mat[MATSIZE][MATSIZE];

void gen_mat()
{
int i =0,j;
int real;
int img;
for( ;i < MATSIZE; i++)
{
srand(time(NULL));
real = rand()%RAND_RANGE + 1;
srand(time(NULL));
img = rand()%RAND_RANGE + 1;
for(j = MATSIZE; j != i ; j--)
{
mat[i][j] = real + img * I;
mat[j][i] = conj(mat[i][j]);
}
srand(time(NULL));
if(i == j)
mat[i][i] = rand()%RAND_RANGE + 0*I;
}
}

void print_mat()
{
int i,j;
for(i = 0; i < MATSIZE; i++)
{
for(j = 0; j < MATSIZE; j++)
{
printf("%f + %f *i", creal(mat[i][j]), cimag(mat[i][j]));
printf(" ");
}
puts("\n");
}
}

int main()
{
gen_mat();
print_mat();
return 0;
}

示例输出

[aft@centos-c physics-numaric]$ ./a.out 
66.000000 + 0.000000 *i 67.000000 + 67.000000 *i 67.000000 + 67.000000 *i 67.000000 + 67.000000 *i 67.000000 + 67.000000 *i

67.000000 + -67.000000 *i 66.000000 + 0.000000 *i 67.000000 + 67.000000 *i 67.000000 + 67.000000 *i 67.000000 + 67.000000 *i

67.000000 + 67.000000 *i 67.000000 + -67.000000 *i 66.000000 + 0.000000 *i 67.000000 + 67.000000 *i 67.000000 + 67.000000 *i

67.000000 + 67.000000 *i 67.000000 + -67.000000 *i 67.000000 + -67.000000 *i 66.000000 + 0.000000 *i 67.000000 + 67.000000 *i

67.000000 + 67.000000 *i 67.000000 + -67.000000 *i 67.000000 + -67.000000 *i 67.000000 + -67.000000 *i 66.000000 + 0.000000 *i

编辑在 main() 中调用 srand 实际上解决了问题。谢谢你们。

[aft@centos-c physics-numaric]$ ./a.out 
31.000000 + 0.000000 *i 81.000000 + 75.000000 *i 81.000000 + 75.000000 *i 81.000000 + 75.000000 *i 81.000000 + 75.000000 *i

81.000000 + -75.000000 *i 53.000000 + 0.000000 *i 69.000000 + 57.000000 *i 69.000000 + 57.000000 *i 69.000000 + 57.000000 *i

69.000000 + 57.000000 *i 69.000000 + -57.000000 *i 27.000000 + 0.000000 *i 93.000000 + 11.000000 *i 93.000000 + 11.000000 *i

93.000000 + 11.000000 *i 69.000000 + -57.000000 *i 93.000000 + -11.000000 *i 58.000000 + 0.000000 *i 76.000000 + 78.000000 *i

76.000000 + 78.000000 *i 69.000000 + -57.000000 *i 93.000000 + -11.000000 *i 76.000000 + -78.000000 *i 67.000000 + 0.000000 *i

最佳答案

不要在每次调用 rand 之前调用 srand。程序启动时调用一次。

关于c - rand() 不返回随机值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10259028/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com