使用rand()函数的随机数矩阵乘法

时间:2016-02-22 23:52:15

标签: c matrix-multiplication dynamic-memory-allocation

以下是使用rand()函数的随机数矩阵乘法的代码。程序的输出给出了非常大的值作为矩阵元素。

  

为什么不生成任何小的随机数?

这是N = 3时的输出

输入N:3

的值

Final Matrix:

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);
}

1 个答案:

答案 0 :(得分:0)

使用模运算符获取较小的值(例如rand()%100)。虽然这种方式略微不均匀分布,但这不应成为问题。 - Ctx