簡體   English   中英

列出c中數組的數字內容

[英]Listing numerical contents of an array in c

我正在編寫一個簡單的程序,該程序獲取一個成績列表,並在c中輸出及格成績,並列出列表中的所有成績(10個成績)。

計算合格成績並打印出來的功能很好。

我遇到問題的地方是使用printf打印數組的內容。

這是我輸入數組的方式:

int grades[10] = {70, 80, 95, 65, 35, 85, 54, 78, 45, 68};

目前,我正在使用此功能(有效):

printf ("These are the grades: %d, %d, %d, %d, %d, %d, %d, %d, %d, %d \n", grades[0], grades[1], grades[2], grades[3], grades[4], grades[5], grades[6], grades[7], grades[8], grades[9]);

它列出了數組的內容,但是我確信必須有一種更優雅的方式來打印列表,而不要專門指向數組的每個元素。

我沒有意識到更優雅的解決方案嗎?

我確實搜索了主題,但找不到答案,如果這是重復的,對不起。

您需要編寫一個函數來接收成績作為參數並打印出來!

void print_array(int* grades, int size) {
   for(int i = 0; i  < size; i++) {
     printf("%d", grades[i]);
   }
}

使用控制循環(在本例中for )來打印您要定位的任意數量的項目。 給定要打印的N個項目的數組,以下內容對此進行了演示(並產生了您所需的確切輸出):

int grades[N]; // initialized here or filled later

printf("These are the grades: %d", grades[0]);
for (int i = 1; i  < N; i++) 
    printf(", %d", grades[i]);
fputc('\n', stdout);

請注意,這種方法允許您對陣列進行欠打印 您不必打印所有內容 例如,假設您有一個可以容納M項目,但僅容納N (其中0 <= N <= M容納)的數組。 然后,只需更改現有算法,以解決可能更少的項目(包括所有項目):

if (N > 0)
{
    printf("These are the grades: %d", grades[0]);
    for (int i = 1; i  < N; i++) 
        printf(", %d", grades[i]);
    fputc('\n', stdout);
}

您可以在此處找到有關for循環的更多信息,以及C語言的許多其他屬性。 保持聯系; 值得收藏。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM