小弟最近在學習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嗎>"<
感恩~~
但是在你還沒有按下enter時,他不會有反應
但是你按下enter時,也算一個字元
也就是你打一個字母,再按一個enter,就經過2次 getchar()了
你找最小沒有東西印出來,就是因為enter是比你的字母小,故是印出enter,但你沒看到
如果一次輸入6個字母,再按enter
這個enter就不會被getchar抓到了
這樣程式執行就是對的
內文搜尋

X