C语言 if-else语句
在C语言编程中,if-else语句被用于决策。如果给定的条件为真,那么就执行if块内的代码,否则就执行else块代码。任何非零和非空的值都被认为是真值,而零或空的值被认为是假值。
语法:
if(condition) {
// execute statement of if block when
// condition is true
}
else {
// execute statement of else block when
// condition is false
}
// C Program to show the if...else statement
#include <stdio.h>
int main()
{
int a = 10;
if (a < 20) {
printf("Given Value is less than 20\n");
}
else {
printf("Given Value is greater than 20");
}
return 0;
}
输出
Given Value is less than 20
优势。
- if-else语句帮助我们在编程中做出决定并执行正确的代码。
- 它还有助于调试代码。
劣势。
- if-else语句增加了要测试的代码路径的数量。
- 如果有大量的if语句,代码有时会变得难以阅读和复杂。
例1:检查一个数字是奇数还是偶数
// C Program to find the
// odd and even number using
// if else statement
#include <stdio.h>
int main()
{
int num = 5;
if (num % 2 == 0)
{
// if number is a multiple of 2 then
// the remainder will be 0
printf("%d is even number", num);
}
else
{
// else the remainder will be odd
printf("%d is a odd number", num);
}
return 0;
}
输出
5 is a odd number
注意: 当我们的id里面只有一行代码的时候,否则我们可以跳过大括号。
例2.检查该人是否超过20岁
// C Program to Demonstrate
// the example of if
// else statement
#include <stdio.h>
int main()
{
int age = 25;
if (age < 20)
printf("Age less than 20");
else
printf("Age greater than 20");
return 0;
}
输出
Age greater than 20