• 2

想問一個c語言程式的bug(很簡單的程式>"

小弟最近在學習c語言
不過練習其中一個題目是這樣子的
『讓程式可以輸入5個英文單字,
並且輸出最小的單字(a~z,a是最小的)』

我寫出來的程式是這樣子

#include

main()
{
int i;
char ch,smallest='z';

for(i=0;i<6;i++)
{
printf("Input the char:\n");
ch=getchar();
if(ch<smallest) smallest=ch;
}
printf("最小的英文字是:%c\n",smallest);
}



可是很奇怪的是執行結果完全不是我想要的,
不但Input the char:出現兩行
然後最後小的單字沒有顯示出來,
而且只能輸入三次英文單字


Input the char:
a
Input the char:
Input the char:
b
Input the char:
Input the char:
c
Input the char:
最小的英文字是:

Press any key to continue




但是如果我把程式改成顯示大的英文單字

#include

main()
{
int i;
char ch,smallest='a';

for(i=0;i<6;i++)
{
printf("Input the char:\n");
ch=getchar();
if(ch>smallest) smallest=ch;
}
printf("最大的英文字是:%c\n",smallest);
}



結果還是只能輸入三次單字,
但是這次卻可以輸出最大的單字,

Input the char:
a
Input the char:
Input the char:
b
Input the char:
Input the char:
c
Input the char:
最大的英文字是:c

Press any key to continue



我實在是找不出問題出在那裡
可以請版上的高手幫我看一下bug嗎>"<
感恩~~
2006-09-27 22:33 發佈
#include <stdio.h>

main()
{
int i;
char ch,smallest='z';

for(i=0;i<6;i++)
{
printf("Input the char:\n");
ch=getchar();
printf("%c", ch);

if(ch<smallest)
smallest=ch;
}
printf("最小的英文字是:%c\n",smallest);
}
好像 也回錯了 哈哈哈

getchar()雖然是一次抓一個字元
但是在你還沒有按下enter時,他不會有反應
但是你按下enter時,也算一個字元
也就是你打一個字母,再按一個enter,就經過2次 getchar()了

你找最小沒有東西印出來,就是因為enter是比你的字母小,故是印出enter,但你沒看到

如果一次輸入6個字母,再按enter
這個enter就不會被getchar抓到了
這樣程式執行就是對的
程式應該是沒啥錯
我猜你是 a "enter" b "enter" c "enter"
所以你輸入了 6 次
然後
最大為c
最小為 "enter"
ch=getchar();
改成
ch = getch() ;
printf("%c\n", ch) ;
兩個問題!

1. 你的for loop 會跑六次!

2. getchar() 會讀 enter , 所以你的for loop 只能讓你輸入 6/2 = 3 個英文字母
喔喔喔 我真的是先按 a-->Enter-->b-->Enter-->c-->Enter
我找了兩個小時的bug
大大只花一點時間就解決了>"<
這裡果然臥花藏龍

那請問這樣子的程式可以改良成
提示一次Input the char:
輸入一次字母
然後提示一次…輸入一次………
然後也是用getchar()方式寫嗎??
感覺上是你輸入的時候
把enter也當作一個字元了
所以會出現五次提示句
但是只有三個輸入文字
然後最小的值其實是enter
重劍無鋒,大巧不工
你是不是按完a,b,c 後都有按"Enter", 如果我想的沒錯, 你只要不按"Enter", 你原來的程式就可work 了.

已經10多年沒寫C程式了, 對這些functions 也不太記得了, 但看你的描述, 應是getchar 只會反應對應的keystroke, 按"a" 再按 "Enter", 就會用掉二次loop 了. 希望有所幫助, 如果不是, 只好請其他高手幫忙了, 老夫實在太久沒練功了......
  • 2
內文搜尋
X
評分
評分
複製連結
Mobile01提醒您
您目前瀏覽的是行動版網頁
是否切換到電腦版網頁呢?