查看單個文章
  #1  
舊 2014-02-23, 11:04 PM
哈啦 的頭像
哈啦 哈啦 目前離線
論壇管理員
 
註冊日期: 2002-05-28
文章: 23,020
預設 C語言在一堆數字中求眾數的問題

書上的例題,輸入二十個任意數字,然後求出現最多的那個數字。看書上用mode來代表那個數的名稱,本來還不懂為啥用mode(模式?),後來查一下才知道mode也叫「眾數」,就是一組數字中最常出現的那個數字就叫mode(眾數 Mode 指一組數據中出現次數最多的變數值)。真長了知識。

但這題真的是有看沒有懂,從oldcount=0;以下,看了一頭霧水。

代碼:
#include <stdio.h>

int main(void)
{
        int stats[20],x,y;
        int mode,count,oldcount,oldmode;
        
        printf("enter 20 numbers: \n");
        for(x=0;x<20;x++) scanf("%d",&stats[x]);
        
        oldcount = 0;

        //find the mode
        
        for(x=0;x<20;x++){
                mode=stats[1];
                count =1;
                
                //count the occurrences of this value.
                
                for(y=x+1;y<20;y++)
                if(mode==stats[y]) count++;
                
                //if count is greater than old count,use new mode.
                if(count>oldcount){
                        oldmode=mode;
                        oldcount=count;
                }
        }
        printf("the mode is %d\n",oldmode);
        return 0;
}
__________________
咖啡走路
微博


您是網站站長嗎?歡迎到站長俱樂部 一起討論吧。
按我看版規
code.club
回覆時引用此篇文章