C Nếu ... Ví dụ khác
Ví dụ thực tế đời sống
Ví dụ này cho thấy cách bạn có thể sử dụng if..else
để "mở cửa" nếu người dùng nhập đúng mã:
Ví dụ
int doorCode = 1337;
if (doorCode == 1337) {
printf("Correct
code.\nThe door is now open.");
} else {
printf("Wrong code.\nThe
door remains closed.");
}
Hãy tự mình thử » Ví dụ này cho thấy cách bạn có thể sử dụng if..else
để tìm hiểu xem một số là dương hay âm:
Ví dụ
int myNum = 10; // Is this a positive or negative number?
if (myNum >
0) {
printf("The value is a positive number.");
} else if (myNum
< 0) {
printf("The value is a negative number.");
} else {
printf("The value is 0.");
}
Hãy tự mình thử »Tìm hiểu xem một người có đủ tuổi để bỏ phiếu hay không:
Ví dụ
int myAge = 25;
int votingAge = 18;
if (myAge >= votingAge) {
printf("Old enough to vote!");
} else {
printf("Not old enough
to vote.");
}
Hãy tự mình thử »Tìm hiểu xem một số là chẵn hay lẻ:
Ví dụ
int myNum = 5;
if (myNum % 2 ==
0) {
printf("%d is even.\n",
myNum);
} else {
printf("%d is odd.\n", myNum);
}
Hãy tự mình thử »