簡單記錄下今日所學內容...
1.關於if else語句我們先來舉一個簡單的例子
#include<stdio.h>
#include<stdlib.h>
int main(){
int choice = 0;
printf("你會願意寫代碼嗎?(1 or 0):");
scanf("%d", &choice);
//第一種寫法有
if (choice == 1) {
printf("好offer在向你招手!\n");
}
else {
printf("回家賣紅薯吧!\n");
}
system("pause");
return 0;
}
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
#include<stdio.h>
#include<stdlib.h>
int main(){
//第二種寫法有
if (choice == 1) {
printf("好offer在向你招手!\n");
}
else if(choice==0){
printf("回家賣紅薯吧!\n");
}
else {
printf("錯誤的輸入\n");
}
system("pause");
return 0;
}
從上邊這個例子可以看出來,選擇分支語句會提升代碼可能結果的多樣性,使代碼包含的內容更全面。
2.在選擇語句中有很多需要注意的地方,比如:
在下邊這兩個語句中,相比於語句2而言,語句1相對來說就比較簡潔,易於人觀察,並且更容易讓人不出錯。
int Func1() {
if (!condition1) {
return 1;
}
if (!condition2) {
return 1;
}
DoSomeThing();
return 0;
}
int Func2() {
if (condition1) {
if (condition2) {
DoSomeThing();
return 0;
}
}
else {
return 1;
}
}
3.再舉一個例子
#include<stdio.h>
#include<stdlib.h>
int main(){
int num = 3;
if (num == 10) {
printf("hehe\n");
}
else {
printf("haha\n");
}
system("pause");
return 0;
}
此時的打印結果爲:haha.
再試想下如果此時num==10改爲num=10的話,程序將走到第一種情況下,打印結果爲hehe.
將上邊的代碼稍加改動會避免漏掉“=”的失誤.
#include<stdio.h>
#include<stdlib.h>
int main(){
int num = 3;
if (10 == num) {
printf("hehe\n");
}
else {
printf("haha\n");
}
system("pause");
return 0;
}
不過在這裏還是比較推薦寫第一種代碼.
以上就是今日所學內容,後面會持續更新丫....
待更....