C语言 if...else语句的用法

315 阅读1分钟

C - if...else语句

在C语言中,if-else语句被用来做决策。如果给定的条件是真的,那么就执行if块内的代码,否则就执行else块代码。任何非零和非空的值都被认为是真值,而零或空的值被认为是假值。

语法。

if(conition) {
        // execute statement of if block when
          // condition is true
    }
      else {
        // execute statement of else block when
          // condition is false
    }

C

// 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 in C

优点。

  • if-else语句帮助我们在编程中做出决定并执行正确的代码。
  • 它也有助于调试代码。

缺点。

  • if-else语句增加了需要测试的代码路径的数量。
  • 如果有大量的if语句,代码有时会变得不可读和复杂。

例1:检查一个数字是奇数还是偶数

C++

// 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或else里面只有一行代码的时候,我们可以跳过大括号。

例2.检查这个人是否在20岁以上

C

// 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