使用 rand() 函数对随机数进行矩阵乘法
Matrix Multiplication of random numbers using rand() function
这是使用 rand()
函数对随机数进行矩阵乘法的代码。该程序的输出给出了非常大的值作为矩阵元素。
Why not any small random numbers not generated??
这是N=3时的输出
输入 N 的值:3
最终矩阵:
259448206-96933429-936226671
-409898077185182340844598571
-1916994436-653447116470937338
节目:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
time_t t;
int **ptr1, **ptr2, **ptr3;
int N, col1, row2, col2;
srand ((unsigned) time (&t));
int i, j, k;
printf ("\nEnter the value of N : ");
scanf ("%d", &N);
ptr1 = (int **) malloc (sizeof (int *) * N);
ptr2 = (int **) malloc (sizeof (int *) * N);
ptr3 = (int **) malloc (sizeof (int *) * N);
for (i = 0; i < N; i++)
ptr1[i] = (int *) malloc (sizeof (int) * N);
for (i = 0; i < N; i++)
ptr2[i] = (int *) malloc (sizeof (int) * N);
for (i = 0; i < N; i++)
ptr3[i] = (int *) malloc (sizeof (int) * N);
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
ptr1[i][j] = rand ();
}
}
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
ptr2[i][j] = rand ();
}
}
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
ptr3[i][j] = 0;
for (k = 0; k < N; k++)
ptr3[i][j] = ptr3[i][j] + ptr1[i][k] * ptr2[k][j];
}
}
/* Printing the contents of third matrix. */
printf ("\n\nFinal Matrix :");
for (i = 0; i < N; i++) {
printf ("\n\t");
for (j = 0; j < N; j++)
printf ("%4d", ptr3[i][j]);
}
printf ("\n");
return (0);
}
使用取模运算符获得更小的值(例如 rand()%100)。虽然它以这种方式稍微不均匀分布,但这在这里不应该成为问题。 – Ctx
这是使用 rand()
函数对随机数进行矩阵乘法的代码。该程序的输出给出了非常大的值作为矩阵元素。
Why not any small random numbers not generated??
这是N=3时的输出
输入 N 的值:3
最终矩阵:
259448206-96933429-936226671
-409898077185182340844598571
-1916994436-653447116470937338
节目:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
time_t t;
int **ptr1, **ptr2, **ptr3;
int N, col1, row2, col2;
srand ((unsigned) time (&t));
int i, j, k;
printf ("\nEnter the value of N : ");
scanf ("%d", &N);
ptr1 = (int **) malloc (sizeof (int *) * N);
ptr2 = (int **) malloc (sizeof (int *) * N);
ptr3 = (int **) malloc (sizeof (int *) * N);
for (i = 0; i < N; i++)
ptr1[i] = (int *) malloc (sizeof (int) * N);
for (i = 0; i < N; i++)
ptr2[i] = (int *) malloc (sizeof (int) * N);
for (i = 0; i < N; i++)
ptr3[i] = (int *) malloc (sizeof (int) * N);
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
ptr1[i][j] = rand ();
}
}
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
ptr2[i][j] = rand ();
}
}
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
ptr3[i][j] = 0;
for (k = 0; k < N; k++)
ptr3[i][j] = ptr3[i][j] + ptr1[i][k] * ptr2[k][j];
}
}
/* Printing the contents of third matrix. */
printf ("\n\nFinal Matrix :");
for (i = 0; i < N; i++) {
printf ("\n\t");
for (j = 0; j < N; j++)
printf ("%4d", ptr3[i][j]);
}
printf ("\n");
return (0);
}
使用取模运算符获得更小的值(例如 rand()%100)。虽然它以这种方式稍微不均匀分布,但这在这里不应该成为问题。 – Ctx