2014-04-04 48 views
0

我是一個嘗試用隨機數填充3x5二維數組的初學者,然後在屏幕上顯示高,低和平均值。我無法讓我的陣列打印到屏幕上。有人可以幫忙嗎?用隨機數填充數組並打印到屏幕

#include <stido.h> 
#include <math.h> 
#include <time.h> 

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

你需要將'printf'命令放入'row'和'col'的循環中;或者,如果您首先要計算數組並​​然後*打印它們,請重複循環打印。 – usr2564301

+2

'#include '不存在,它是'#include '。 – Biduleohm

+0

我的數組打印錯誤,它不會停止添加nubers,你能幫我嗎? – user3479702

回答

3

您已經3個主要問題:

作爲Jongware在他的評論說,printf應的循環,不在外面裏面。

2.#include <stido.h>不存在,這是#include <stdio.h>

row +1row = row + 1,或row += 1,或row++,或者++row(在這種情況下,我們通常用row++++row)。當然,你需要爲col


次做同樣的:

一個。practice_arrayi在這裏沒用。

b。你可能忘了printf中的\n


我糾正你的代碼+我加了最小值,最大值和平均值:

#include <stdio.h> 
#include <math.h> 
#include <time.h> 

#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); 
} 
+0

+1好的編輯。幾乎沒有後續評論。你可能不需要'我'了。如果在整行之後打印,而不是每個元素,「\ n」可能會更好看。您可能需要添加計算代碼並顯示高,低和平均值。 – Arun

+0

@阿倫你說得對,我會編輯,謝謝;) – Biduleohm

1

你不能像這樣打印數組。每個元素必須由它自己打印。

for (row = 0; row < 3; row++){ for (col = 0; col < 5; col++){ printf ("%d ", array[row][col]); } }

0

有在我爲您解決代碼各種事情。

要包括該庫是stdio.h 山口和行的價值不能被正確 更新和printf聲明需要去在環路和打印每個值,因爲它是popul

include <stdio.h> 
include <math.h> 
include <time.h> 

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