阿摩線上測驗 登入

申論題資訊

試卷:107年 - 107 高等考試_三級_資訊處理:程式語言#70822
科目:程式語言
年份:107年
排序:5

題組內容

四、請撰寫一支完整的 C/C++程式,此程式包含一個一維陣列,陣列元素的個數由使用 者輸入,陣列元素值由時間亂數產生,數值範圍介於在 1(含)至 99(含)間。此 程式需包含下列函數:

申論題內容

⑵ arrBubble():將所傳入的一維陣列利用氣泡排序法將陣列元素由小至大排序。 (10 分)

詳解 (共 1 筆)

詳解 提供者:Phil(112高普雙榜)

其C++程式碼如下(含第一小題功能)-

#include<iostream>

#include<cstdlib>  //亂數時間函數

#include<ctime>  //亂數時間函數

using namespace std;

int arrMean(int arr[],int n){

    int sum1=0;

    for(int j=0;j<n;j++){

        sum1+=arr[j];

    }

    double avg=sum1/n;

    return avg;

}

void arrBubble(int arr[],int n){

    cout<<"執行氣泡排序前:";

    for(int q=0;q<n;q++){

        cout<<arr[q]<<" ";

    }

    for(int p=n-1;p>=1;p--){

        for(int k=0;k<p;k++){

            if(arr[k]>arr[k+1]){

               int temp=arr[k];

               arr[k]=arr[k+1];

               arr[k+1]=temp;  

            }

            else{

               continue;

            } 

        }

    }

    cout<<endl;

    cout<<"執行氣泡排序後:";

    for(int r=0;r<n;r++){

        cout<<arr[r]<<" ";

    }

}

int main()

{

    srand(time(NULL));

    int random=(rand()%99)+1;

    int a[random]={0};

    cout<<"請輸入數字(本次一共可輸入"<<random<<"個數字,輸入數字可不按順序輸入。):"<<endl;

    for(int i=0;i<random;i++){

        cin>>a[i];

    }

    double catch_avg=arrMean(a,random);

    cout<<"本次輸入結果之平均值為:"<<catch_avg<<endl;

    arrBubble(a,random);

    return 0;

}