1. 程式人生 > >陣列遍歷及求和(C語言)

陣列遍歷及求和(C語言)

最近學習了C語言的入門,作為陣列的綜合練習,在此寫下相關經驗及程式碼。

題目:在一個長度為10的整型數組裡面,儲存了班級10個學生的考試成績。要求編寫5個函式,分別實現計算考試的總分,最高分,最低分,平均分和考試成績降序排序。

程式碼部分:

#include <stdio.h>
int totalClass(int score[])//求班級總分
{
    int sum = 0;
    for(int i=0;i<=9;i++)//陣列中每門成績遍歷加求和
    {
        sum += score[i];
    }
    return sum;
}
int maxClass(int score[])//求班級分數最高分
{
   for(int i=0; i<=9;i++)//只需要用一組冒泡,最後一個即為最大值
   {
        if(score[i]>score[i+1])//大的數換到最後
           {
                int temp; 
                temp = score[i];
                score[i] = score[i+1];
                score[i+1] = temp;
           }
    }
    return score[9];
}
   
int minClass(int score[])//求班級分數最低分

{
    for(int i=0;i<=9;i++)//冒泡同理,求最小值,並替換
    {
        if(score[i]>score[i+1])
           {
                int temp; 
                temp = score[i];
                score[i] = score[i+1];
                score[i+1] = temp;
           }
    }
    return score[1];
}
    
int aveClass(int score[])//求班級平均分,直接在求和基礎上除以班級人數
{
    int sum = 0;
    for(int i=0;i<=9;i++)
    {
        sum += score[i];
    }
    return sum/10;
}
int seqClass(int score[])//班級考試分數降序排序;
{
    printf("班級10個學生的考試降序排序為: ");
       for(int i=9; i>=0;i--)//幾輪迴圈
   {
       for(int j=0;j<=i;j++)//找最小值放後面
       {
           if(score[j]>score[j+1])
           {
                int temp; 
                temp = score[j];
                score[j] = score[j+1];
                score[j+1] = temp;
           }
           
       }
       printf("%d,",score[i]);
   }
 
}
int main()
{
    int score[10]={67,98,75,63,82,79,81,91,66,84};
    printf("班級10個學生的考試總分為:%d\n",totalClass(score));
    printf("班級10個學生的考試最高分為:%d\n",maxClass(score));
    printf("班級10個學生的考試最低分為:%d\n",minClass(score));
    printf("班級10個學生的考試平均分為:%d\n",aveClass(score));
    seqClass(score);
    return 0;
}
執行結果顯示如下:
班級10個學生的考試總分為:786
班級10個學生的考試最高分為:98
班級10個學生的考試最低分為:63
班級10個學生的考試平均分為:78
班級10個學生的考試降序排序為: 98,91,84,82,81,79,75,67,66,63,
只要你認真學習,仔細揣摩,所有的事情都會很簡單。