C 语言的条件运算符

条件运算符 (conditional operator) 是唯一一个三元运算符.

格式: 表达式 1 ? 表达式 2 : 表达式 3

以上构成一个条件表达式 (conditional expression).

当表达式 1 为真时, 条件运算表达式的值为表达式 2 的值, 否则条件运算表达式的值为表达式 3 的值.

表达式1为真,则只算表达式2,表达式3不计算。表达式1为假,则只算表达式3,表达式2不算。

条件运算符的结合方向是自右至左.

条件表达式可以嵌套, 即其中的表达式又是一个条件表达式.

int a, b, c, d;
a > b ? a : c > d ? c : d;

相当于:

a > b ? a : (c > d ? c : d);

条件运算符可以替代 if else, 代码更加简洁, 编译器生成的机器码也更简洁.

程序示例:

#include<stdio.h>
#define COVERAGE 200  // 每一罐油漆可以粉刷的面积
int main(void)
{
	int sq;  // 需要粉刷的面积
	int cans;  // 需要的罐数
	printf("Enter the square to be painted (Enter q to quit): ");
	while (scanf("%d", &sq) == 1)
	{
		cans = sq / COVERAGE;
		cans = sq % COVERAGE == 0 ? cans : cans + 1;
		printf("You need %d %s.\n", cans, cans == 1 ? "can" : "cans");
		printf("Enter the square to be painted (Enter q to quit): ");
	}

	return 0;
}

结果:

Enter the square to be painted (Enter q to quit): 199
You need 1 can.
Enter the square to be painted (Enter q to quit): 200
You need 1 can.
Enter the square to be painted (Enter q to quit): 201
You need 2 cans.
Enter the square to be painted (Enter q to quit): q
  • 6
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值