查找數組中的眾數


  輸入10個整型數據到數組中,查找眾數(輸入次數最多的那個數)

#include <stdio.h>
#include <stdlib.h>>

struct node{  //定義一個結構體,用於記錄數字出現的次數
  int x;
  int x_number;
};


int main(void)
{
  int array[10];
  int i,j;
  int flag=0;
  int index=1;
  int max,max_idex;
  struct node node_array[10] = { 0 };  //計數數組(定義數數組記錄出現的數字)
  printf("請輸入數組\n");
  for (i = 0; i < 10; i++)        //輸入10個整型數字
  {
     scanf("%d", array + i);
  }
  printf("輸入的數組為:");
  for (i = 0; i < 10; i++)        //打印
  {
    printf(" %d\t", array[i]);
  }
  printf("\n");

  for (i = 0; i < 10; i++)        //遍歷數組
  {
    if (array[i] == 0)        //把數字0存儲在第一個元素中
    {
      node_array[0].x_number += 1;  //如果出現0 計數++
      continue;            //繼續遍歷
    }
    for (j = 0; j < 10; j++)      
    {  
      if (array[i] == node_array[j].x)  //查找數中的元素是否已經計數
      {
        node_array[j].x_number++;  //如果已經計數,計數++
        flag = 1;
        continue;        //繼續遍歷
      }
    }
    if (flag == 0)      //遍歷的元素沒有開始計數
    {
      node_array[index].x = array[i];  //添加到計數數組
      node_array[index].x_number += 1;
      index++;
    }
    flag = 0;
  }
  max = node_array[0].x_number;
  max_idex = 0;
  for (i = 0; i < index-1; i++)    //查找計數數組中計數最大的元素
  {
    if (max < node_array[i + 1].x_number)
    {
      max = node_array[i + 1].x_number;
      max_idex = i + 1;    //計數數組中計數最大的元素的下標
    }
  }
  printf("眾數為:%d\t出現次數為:%d\n", node_array[max_idex].x, node_array[max_idex].x_number);

system("pause");
return 0;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM