尋找陣列中的眾數
阿新 • • 發佈:2019-01-28
原始碼:
#include<stdio.h> #include<stdlib.h> #include<time.h> int main(){ int a[100],temp; int max1=0,max2=1; int p[100]={0},z=0; //利用rand函式產生一個隨機陣列 srand((unsigned)time(NULL)); for(int i=0;i<100;i++){ a[i]= rand() % 100; } //找出眾數的思想是:先排序,然後找出那個重複最多的數,那個數就是眾數了 //①先利用氣泡排序法對陣列進行排序 for(int b=0;b<99;b++){ for(int c=0;c<99-b-1;c++){ if(a[c]>a[c+1]){ temp=a[c]; a[c]=a[c+1]; a[c+1]=temp; } } } //②找出陣列中重複最多的那個數,也就是眾數,先找出眾數出現的次數(出現的次數是max1) for(int d=0;d<99;d++){ if(a[d]==a[d-1]){ max2=max2+1; } if(max2>max1){ max1=max2; } if(a[d]!=a[d+1]){ max2=1; } } max2=1; //③將陣列的眾數提取出來儲存在陣列p[100]中 for(int d=0;d<99;d++){ if(a[d]==a[d-1]){ max2=max2+1; } if(max2==max1){ p[z]=a[d]; z++; } if(a[d]!=a[d+1]){ max2=1; } } //輸出 printf("這個陣列為:\n"); for(int j=0;j<99;j++){ printf("%d ",a[j]); } printf("\n"); printf("這個陣列的眾數為:\n"); for(int j=0;p[j]!='\0';j++){ printf("%d ",p[j]); } return 0; }