用随机数填充数组并打印到屏幕
我是初学者,尝试用随机数填充3×5二维数组,然后在屏幕上显示高,低和平均值。 我无法让我的arrays打印到屏幕上。 有人可以帮忙吗?
#include #include #include int main (void){ int array [3][5]; int practice_array; int i, row, col; srand(time(NULL)); for ( row = 0; row < 3; row +1){ for ( col = 0; col < 5; col +1){ array[row][col] = (rand()%10000) + 1; } } practice_array = array[row][col]; printf("%d", array[row][col]); return (0); }
你有3个主要问题:
正如Jongware在评论中所说, printf
应该在循环内,而不是在外面。
2. #include
不存在,它是#include
3. row +1
应为row = row + 1
,或row += 1
,或row++
,或++row
(在本例中我们通常使用row++
或++row
)。 当然你需要为col
做同样的事情
二级:
一个。 practice_array
, i
在这里没用。
湾 你可能忘记了printf
的\n
。
我更正了你的代码+我添加了最小值,最大值和平均值:
#include #include #include #define ROWS_NB 3 #define COLS_NB 5 #define MIN_VAL 1 #define MAX_VAL 10000 int main(void) { int array[ROWS_NB][COLS_NB]; int row; int col; int val; int min = MAX_VAL; int max = MIN_VAL; int avg = 0; srand(time(NULL)); for (row = 0; row < ROWS_NB; ++row) { for (col = 0; col < COLS_NB; ++col) { val = (rand() % (MAX_VAL - MIN_VAL)) + MIN_VAL; if (val < min) min = val; else if (val > max) max = val; avg += val; array[row][col] = val; //printf("%d ", val);/* uncomment if you want to print the array */ } //printf("\n");/* uncomment if you want to print the array */ } avg /= ROWS_NB * COLS_NB; printf("min: %d\nmax: %d\naverage: %d\n", min, max, avg); return (0); }
你不能只打印那样的数组。 每个元素必须由它自己打印。
for ( row = 0; row < 3; row++){ for ( col = 0; col < 5; col++){ printf ("%d ", array[row][col]); } }
我为你修复的代码中有各种各样的东西。
你想要包含的库是stdio.h
col和row的值没有正确更新, printf
语句需要进入循环并打印每个值,因为它是popul
include include include int main (void) { int array [3][5]; int i, row, col; srand(time(NULL)); for ( row = 0; row < 3; row++) { for ( col = 0; col < 5; col++) { array[row][col] = (rand()%10000) + 1; printf("%d ", array[row][col]); } printf("\n"); } return (0); }