模擬情景
在學校運動會百米比賽之前,老師要求小c同學編寫一個程序,要求輸入成績和性別進行判斷
- 如果用時在10秒內,則進入決賽,否則提示淘汰!
- 並且依據性別進入男子組或者女子組!
思路分析
這裏的時間應該設爲double型,性別應該是char 兩種,男(male)或者女(female),用if嵌套來編寫會比較舒服
基本框架
#include<stdio.h>
int main()
{
double time;
char gender;
printf("請輸入時間(s):");
scanf("%lf",&time);
if(time<=10)
{
這裏得判斷性別,男(m)或者女(f);
}
else
{
printf("很抱歉,你被淘汰了!");
}
return 0;
}
細節研究
很簡單,也是if語句,如果是男(m),就進入男子組,如果是女(f)就進入女子組,
但是
#include<stdio.h>
int main()
{
double time;
char gender;
printf("請輸入時間(s):");
scanf("%lf",&time);
if(time<=10)
{
printf("你已經晉級,現在請輸入性別(gender):");
scanf("%c",&gender);
if(gender=='m')
{
printf("恭喜你進入男子組決賽!");
}
else
{
printf("恭喜你進入女子組決賽!");
}
}
else
{
printf("很抱歉,你被淘汰了!");
}
return 0;
}
這麼寫會出現一個問題,只要輸入時間,直接就判斷了性別
輸入時間成績的時候,會默認得輸入"回車", 注意!!注意!!注意!!
接下來的 scanf("%c",&gender)會接收到這個"回車"
所以得加一句!消除這個"回車"的影響!
#include<stdio.h>
int main()
{
double time;
char gender;
printf("請輸入時間(s):");
scanf("%lf",&time);
if(time<=10)
{
printf("你已經晉級,現在請輸入性別(gender):");
scanf("%c",&gender); //這個是消除"回車鍵"的影響!
scanf("%c",&gender); //這個是輸入性別 !
if(gender=='m')
{
printf("恭喜你進入男子組決賽!");
}
else
{
printf("恭喜你進入女子組決賽!");
}
}
else
{
printf("很抱歉,你被淘汰了!");
}
return 0;
}