4

C 语言教程:条件和 if...else 语句 - 小万哥丶

 8 months ago
source link: https://www.cnblogs.com/xiaowange/p/17926791.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

C 语言中的条件和 if...else 语句

您已经学习过 C 语言支持数学中的常见逻辑条件:

  • 小于:a < b
  • 小于或等于:a <= b
  • 大于:a > b
  • 大于或等于:a >= b
  • 等于:a == b
  • 不等于:a != b

您可以使用这些条件来根据不同的决策执行不同的操作。

C 语言具有以下条件语句:

  • 使用 if 来指定要执行的代码块,如果指定的条件为真
  • 使用 else 来指定要执行的代码块,如果相同的条件为假
  • 使用 else if 来指定要测试的新条件,如果第一个条件为假
  • 使用 switch 来指定要执行的许多备选代码块

使用 if 语句指定要执行的代码块,如果条件为真。

语法

if (condition) { // 要在条件为真时执行的代码块}

请注意,if 是小写字母。大写字母(If 或 IF)会生成错误。

在下面的示例中,我们测试两个值以找出 20 是否大于 18。如果条件为真,则打印一些文本:

if (20 > 18) { printf("20 is greater than 18");}

我们也可以测试变量:

int x = 20;int y = 18;if (x > y) { printf("x is greater than y");}

在上面的示例中,我们使用两个变量 xy 来测试 x 是否大于 y(使用 > 运算符)。由于 x 为 20,y 为 18,并且我们知道 20 大于 18,因此我们在屏幕上打印“x is greater than y”。

else 语句

使用 else 语句指定要执行的代码块,如果条件为假。

语法

if (condition) { // 如果条件为真,则执行的代码块} else { // 如果条件为假,则执行的代码块}
int time = 20;if (time < 18) { printf("Good day.");} else { printf("Good evening.");}// 输出 "Good evening."

在上面的示例中,时间 (20) 大于 18,因此条件为假。因此,我们移动到 else 条件并打印到屏幕“Good evening”。如果时间小于 18,则程序将打印“Good day”。

else if 语句

使用 else if 语句指定新的条件,如果第一个条件为假。

语法

if (condition1) { // 如果条件1为真,则执行的代码块} else if (condition2) { // 如果条件1为假且条件2为真,则执行的代码块} else { // 如果条件1为假且条件2为假,则执行的代码块}
int time = 22;if (time < 10) { printf("Good morning.");} else if (time < 20) { printf("Good day.");} else { printf("Good evening.");}// 输出 "Good evening."

在上面的示例中,时间 (22) 大于 10,因此第一个条件为假。下一个条件,在 else if 语句中,也是假的,因此我们移动到 else 条件,因为 condition1condition2 都是假的 - 并打印到屏幕“Good evening”。

但是,如果时间是 14,我们的程序会打印“Good day”。

另一个例子

此示例展示了如何使用 if..else 找出数字是正数还是负数:

int myNum = 10; // 这是一个正数还是负数? 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.");}

C 语言中的简洁 if...else 语句(三元运算符)

除了标准的 if...else 语句之外,C 语言还提供了一种简写形式,称为三元运算符,因为它由三个操作数组成。它可以将多行代码替换为一行,通常用于替换简单的 if...else 语句。

variable = (condition) ? expressionTrue : expressionFalse;

以下代码用标准的 if...else 语句判断时间是否晚于 18 点:

int time = 20;if (time < 18) { printf("Good day.");} else { printf("Good evening.");}

使用三元运算符可以简写为:

int time = 20;(time < 18) ? printf("Good day.") : printf("Good evening.");

两种方式都将输出 "Good evening."。

三元运算符的优点在于简洁,可以将多行代码替换为一行,使代码更易读。

三元运算符的缺点在于可读性下降,尤其是嵌套使用时,可能会使代码难以理解。

建议在简单的 if...else 语句中使用三元运算符,以简化代码。在复杂的情况下,建议使用标准的 if...else 语句,以保持代码的可读性。

为了方便其他设备和平台的小伙伴观看往期文章:

微信公众号搜索:Let us Coding,关注后即可获取最新文章推送

看完如果觉得有帮助,欢迎 点赞、收藏、关注


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK