語法: ① if (表達式){
語句;
}
② if (表達式){
語句;
}else{
語句;
}
1例題,求用戶輸入的年齡>=30,輸出好好努力,年齡<=30輸出認真學習。
1 #include <stdio.h>
2 int main(){
3 int age=0;
4 printf("請輸入您的年齡:");
5 scanf("%d",&age);
6 if (age>=30){
7 printf("您的年齡狀態 %d歲,請你好好努力!\n",age);
8 }else {
9 printf("您的年齡狀態 %d歲,請你認真學習\n",age);
10 }
11
12 return 0;
13
14
15 }
③: while(表達式){
語句;
}
2.例題,求用戶輸入的整數的位數
1 #include <stdio.h>
2 int main(){
3 int math; //初始化
4 int n=0; //定義統計位數變量
5
6 printf("請輸入數值:");
7 scanf("%d",&math);
8 n++; //因爲最少的位數爲個位所以 初始值n+1
9 math/=10; //除10,留下左邊的位數 比如用戶輸入56,除以10 =5.6 math=5;
10 while(math>0){ //5>0 進入while循環體
11 n++; //n++ N=2;
12 math/=10; //再除10 5/10=0.5; 0.5丟掉 math是整數類型,所以跳出while循環
13
14 }
15 printf("位數是:%d",n);
16 return 0;
17
18 }