【发布时间】:2020-02-23 02:54:22
【问题描述】:
我用 c 语言编写了一个创建随机矩阵的程序。
它创建一个像这样的字符串 (3,-6,2;5,2,-9;-8,20,7)。 “;”削减每一行和一个“,”每一列。现在我写了一个 rust 程序,可以进行矩阵加法或乘法运算。我用这个来称呼它:
./matrix ./test 3 3 "*" ./test 3 3
./matrix 调用我的 rust 程序,我给它 3 个参数。 (矩阵 1、运算符、矩阵 2) 它可以工作并且计算很好,但矩阵 1 和 2 总是相等的。我认为这是因为我根据时间使用 srand 并且因为我同时调用它,它会创建两次相同的结果。我还测试了 Matrixrandomizer,但没有将其包含在我的 rust 调用中,它总是会创建不同的矩阵。
在这里你可以看到我的 c 代码。
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <string.h>
int main (int argc, char* argv[]) {
// Zufallszahlengenerator initialisieren
srand(time(NULL));
if(argc < 3) {
printf("Es fehlen Argumente");
}
char matrix[100] = "";
int r, c;
r = atoi(argv[1]);
c = atoi(argv[2]);
if(r > 0 && c > 0) {
for(int i = 0; i < r; i++) {
for(int j = 0; j < c; j++){
if(j == c - 1) {
int test = (1+rand()%9);
char buffer[50];
sprintf(buffer, "%d", test);
strcat(matrix, buffer);
}
if(j < c - 1){
int test = (1+rand()%9);
char buffer[50];
sprintf(buffer, "%d", test);
strcat(matrix, buffer);
strcat(matrix, ",");
}
}
if(i != r - 1) {
strcat(matrix, ";");
}
}
}
printf("%s", matrix);
}
【问题讨论】:
-
是的,就是这个原因。使用相同的值调用
srand()将使 PRNG 处于相同的状态。如果您使用的是 POSIX 系统,请尝试srand(time(NULL) + getpid()) /* remember to #include <unistd.h> */;(或者对于 Windows 可能是srand(time(NULL) + GetCurrentProcessId()))。 -
什么是
./test 3 3? 3阶随机方阵? -
谢谢 :) 效果很好。 getpid 返回进程的 ID 对吗?因此,当您将其添加到 srand 的种子变量时,您在 srand() 中具有不同的值?
-
./test 3 3 是我对 c 程序的调用,3 3 是矩阵的维度 :)