學長叫我想的(寫得不太好)

11 views
Skip to first unread message

正捷 林

unread,
Apr 10, 2011, 11:24:00 AM4/10/11
to itrs
#include <stdio.h>
#include <stdlib.h>

int main(){
int a[100],n,i,count=0,t;
for(n=0;n<=99;n++){
scanf("%d",&a[n]);
if(a[n]==0) break;
count+=1;
}
for(i=0;i<=count;i++){
for(n=0;n<=count;n++){
if(a[n]<a[n+1])
t=a[n],a[n]=a[n+1],a[n+1]=t;
}
}
for(n=0;n<=count;n++){
printf("%d ",a[n]);

}
system("PAUSE");
return 0;
}

雖然可以比較大小 可是編譯的時候 顯示的字串前面都會有一些莫名其妙的字 拜託學長教教我吧:)

Heron Yang

unread,
Apr 10, 2011, 12:14:30 PM4/10/11
to it...@googlegroups.com
不好意思,
你可以重複一次題目嗎?

另外,
我直接拿你的程式碼編譯沒有看到什麼異常的訊息阿,
要不要把你說莫名其妙的文字貼上來看看?


--
You are subscribed to the "itrs" group, see: http://groups.google.com/group/itrs

kunghua

unread,
Apr 10, 2011, 3:28:09 PM4/10/11
to itrs
我沒編譯這個程式,只是在腦中跑一下,但是有發現下面的問題

首先,下面的 Code 如果中間沒有 0 的話跑完後 count = 100


for(n=0;n<=99;n++){
scanf("%d",&a[n]);
if(a[n]==0) break;
count+=1;
}

接下來

for(i=0;i<=count;i++){
for(n=0;n<=count;n++){
if(a[n]<a[n+1])
t=a[n],a[n]=a[n+1],a[n+1]=t;
}
}

這會跑 101 * 101 次的迴圈,並會用到 a[100] 和 a[101],但是因為你只宣告 a[100] 所以最多只能用 a[0]-
a[99]. 所以你的Code會把 a[100],a[101] 的垃圾拿進你的a[0]-a[99] 陣列中,所以當你輸出的時候就會看到垃圾
值....


應該是這樣....


On Apr 10, 8:14 am, Heron Yang <v6510youn...@gmail.com> wrote:
> 不好意思,
> 你可以重複一次題目嗎?
>
> 另外,
> 我直接拿你的程式碼編譯沒有看到什麼異常的訊息阿,
> 要不要把你說莫名其妙的文字貼上來看看?
>

正捷 林

unread,
Apr 12, 2011, 11:58:59 AM4/12/11
to itrs
題目是[輸入一堆數字 把他們由大到小排列]
所以我之後的迴圈只要把count後面減1就不會有垃圾值了嗎?

李馨怡

unread,
Apr 19, 2011, 12:40:24 AM4/19/11
to it...@googlegroups.com
來個腦筋急轉彎 跟這題無關的
有一堆數字(固定10個好了) 然後輸入其中一個數字 找出排在這個後面的數字
ex.
輸入
12 3 25 19 6 2 21 16 20 7
16
輸出
12
(排序以後 25 21 20 19 16 12 7 6 3 2
12排在16後面)

在 2011年4月12日下午11:58,正捷 林 <joe199...@gmail.com> 寫道:
> 題目是[輸入一堆數字 把他們由大到小排列]
> 所以我之後的迴圈只要把count後面減1就不會有垃圾值了嗎?

kunghua

unread,
Apr 24, 2011, 9:16:12 PM4/24/11
to itrs
我把你的程式重寫了一遍 (我沒有compile 所以不知道能不能執行. LOL). 學弟參考看看吧....

#include <stdio.h>
#include <stdlib.h>
#define SIZE 100

int main()
{
int i,j,count;
int a[SIZE];

for(i=0,count=0;i<SIZE;i++,count++)
{
scanf("%d",&a[i]);

if(a[i]==0) break;
}

// Bubble Sort
for(i=0;i<count;i++)
for(j=i+1;j<count;j++)
if(a[i]<a[j])
a[i]^=a[j]^=a[i]^=a[j]; // This is for your homework....

for(i=0;i<count;i++)
printf("%d ",a[i]);

system("PAUSE");
return 0;
}

On Apr 12, 7:58 am, 正捷 林 <joe1995840...@gmail.com> wrote:
> 題目是[輸入一堆數字 把他們由大到小排列]
> 所以我之後的迴圈只要把count後面減1就不會有垃圾值了嗎?

Reply all
Reply to author
Forward
0 new messages