它是生成随机厄米矩阵的小代码hermitian matrix。rand()不返回随机值
我在每次调用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;
}
样本输出
[[email protected] 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
编辑调用主)函数srand(实际上解决了这个问题。谢谢你们。
[[email protected] 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
如何接受一个答案? – Aftnix 2012-04-21 12:51:57
@aftnix:我认为有一个计时器,所以你只能在问你问题10分钟后接受答案。 – 2012-04-21 12:52:37
查尔斯沃思人真的给了这些堆栈交换应用设计背后的很多想法。很酷的动态:) – Aftnix 2012-04-21 12:55:50