首页
学习
活动
专区
圈层
工具
发布

小朋友学C语言(33):三目运算符

三目运算符(ternary operator),又称条件运算符、三元运算符,是计算机语言(c,c++,java等)的重要组成部分。它是唯一有3个操作数的运算符。 三目运算符的形式为:

代码语言:javascript
复制
<表达式1> ? <表达式2> : <表达式3>

这里先对表达式1进行判断,假如表达式1为真,则执行表达式2;假如表达式1假,则执行表达3。

例1:输入两个数,求最大的数

代码语言:javascript
复制
#include <stdio.h>
int main()
{
    int num1, num2, max;
    printf("Please input 2 numbers, separated by space: ");
    scanf("%d %d", &num1, &num2);
    // 以0或负数作为循环结束的条件 
    while(num1 > 0 && num2 > 0)
    {
        max = num1 > num2 ? num1 : num2;
        printf("max = %d\n", max);
        printf("Please input 2 numbers, separated by space: ");
        scanf("%d %d", &num1, &num2);
    }
    return 0;
}

运行结果:

代码语言:javascript
复制
Please input 2 numbers, separated by space: 3 2
max = 3
Please input 2 numbers, separated by space: 5 10
max = 10
Please input 2 numbers, separated by space: 0 1 
Loop end! Program will be finished!

举报
领券