|
#1
|
||||
|
||||
|
書上的例題,輸入二十個任意數字,然後求出現最多的那個數字。看書上用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;
}
|
|
#2
|
|||
|
|||
|
想法是先假定定一個數字是眾數 mode=stats[0]; (還疑這裡寫錯)
然後去計算第一個數字在這20個數字中出現過幾次,然後去看是否會比 之前眾數次數還多(第一次一定會因為oldcount = 0),假若比之前還多 就把當下的count存入oldcount,然後把現在的數字存入oldmode, 大致上想法是這樣。 |
|
#3
|
||||
|
||||
|
引用:
對於mode=stats[1]這裡,確實是我第一個不解之處,後來你說應是mode=stats[0]也覺得這樣才合理。 後來實際跑了一下,好像原本的寫法答案會出錯。 |
|
#4
|
|||
|
|||
|
另外 mode=stats[0]; 的未置可能也放錯
|
|
#6
|
|||
|
|||
|
請拿2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 (第一個2 後續皆 1)
就會發現書上的out put是2 但是正確答案應為 1 附上我的Code (其實效率不好XD) 代碼:
#include <stdio.h>
#include <iostream>
using namespace std;
int main(void)
{
int num[20];
for(int i=0; i<20; i++)
{
cin >> num[i]; //讀入數字
}
int mode, max_count=0;
for(int i=0; i<20; i++)
{
int count = 0;
for(int j=0; j<20; j++)
{
if(num[i]==num[j])
{
count++; //計算每個數字出現的次數
}
}
if(count>max_count) //假若出現大於之前的則替換
{
max_count = count;
mode = num[i];
}
}
cout << "The mode is " << mode << endl;
}
|
|
#7
|
||||
|
||||
|
thanks.
![]() 我剛才再次拿mode=stats[1];和mode=stats[0];二個都去跑一次,這次果然二個全都是錯誤的結果,剛才我不知怎麼跑的? ![]() 謝謝你的code。 那如果是要修改原本的code,該如何改呢? 真奇怪,如果發生這麼多的錯誤,因為錯誤之處至少二個地方,這本書是如何通過校對的?我目前看的是這本 C語言自學手冊 第三版 ,但我買的比較早,封面不一樣。 跑了一下你的code,在include<iostream>那裡卡住,說沒有這個檔或目錄,後來我改成<iostream.h>也一樣。 另外 using namespace std; 已經超出我目前看過的東西了。 補充,當我看到cin cout時我才想到您寫的是 c++,所以就存成.cpp再去跑,就ok了。 |
|
#8
|
|||
|
|||
|
引用:
代碼:
#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[x]; //這裡應該是要針對每個input去計算應該是每次循環
count = 0; //還沒開始算應該是0不是1,但大家起點相同期實不影響,只是邏輯問題
//count the occurrences of this value.
for(y=0;y<20;y++) //y=x+1會導致前面的沒有算到,count值會錯誤
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;
}
|
|
#10
|
|||
|
|||
|
|