【问题标题】:Trying to print the values in a 2D array尝试打印二维数组中的值
【发布时间】:2018-10-24 17:55:48
【问题描述】:

如标题所示,我正在尝试打印二维数组的值。我的代码如下。我不确定为什么我的代码没有打印结果数组。如下所示,我将制作一个方阵,并在其中给出 0 到 50 之间的随机数。任何想法将不胜感激。非常感谢。

#include <stdio.h>
#include <stdlib.h>

int main () {

    int rows, cols, r, c; 

    printf("Enter the dimension of your square matrix: ");
    scanf("%d", &rows);

    rows=cols; 

    int A[rows][cols]; 

    for (r=0;r<rows;r++){

        for (c=0; c<cols; c++){

            A[r][c]=(rand() % 50); //Generates random number b/w 0 and 50.  

        }



    }

    for (r=0;r<rows;r++){ 

        for (c=0; c<cols; c++){

            printf("%d", A[r][c]);

        }
    }

}

【问题讨论】:

  • 你的代码目前做错了什么?
  • 尝试正确格式化您的代码。
  • 我能够将我的代码运行到我的代码确实要求尺寸的地步,并且我能够输入我选择的数字。但是,它只是不打印结果数组。我没有收到任何错误代码,它编译得很好。
  • rows=cols;cols 尚未设置(rows 已设置)...

标签: c arrays for-loop multidimensional-array random


【解决方案1】:

scanf() 之后覆盖rows 值。 将rows = cols 切换为cols = rows

你也忘了设置 rand 的种子 (srand( time(NULL) ))。

您的代码将如下所示:

int main(){

int rows, cols, r, c; 
srand(time(NULL));

printf("Enter the dimension of your square matrix: ");
scanf("%d", &rows);

cols=rows; 

int A[rows][cols]; 

for (r=0;r<rows;r++){

    for (c=0; c<cols; c++){

        A[r][c]=(rand() % 50); //Generates random number b/w 0 and 50.  

    }

}

for (r=0;r<rows;r++){ 

    for (c=0; c<cols; c++){

        printf("%d ", A[r][c]);

    }
    printf("\n");
}

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-29
    • 2015-08-22
    • 1970-01-01
    • 1970-01-01
    • 2015-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多