C语言比较三个数的5种方法(包含多个三目运算符如何读)

以下程序均在vs2022上编译

1、三目运算符法:需要用到三个三目运算符

程序如下:
 

#include<stdio.h>

int main()
{
    //定义变量
    int a, b, c,max;
    //键入变量
    scanf_s("%d,%d,%d", &a, &b, &c);
    //三目运算符是从右往左读的
    max = a > b ? a > c ? a : c : b > c ? b : c;
    //输出变量
    printf("max = %d\n",max);
    return 0;
}

2、if()else if()else()语句 需要用到逻辑与&&

程序如下:

#include<stdio.h>

int main()
{
    //定义变量
    int a, b, c,max;
    //键入变量
    scanf_s("%d,%d,%d", &a, &b, &c);
 
    if (a > b && a > c)
    {
        max = a;
    }
    else if (b > a && b > c)
    {
        max = b;
    }
    else
    {
        max = c;
    }

    //输出变量
    printf("max = %d\n",max);
    return 0;
}

3、调用外部函数MAX法

程序如下:

#include<stdio.h>

int MAX(int a, int b,int c)
{
     if (a > b && a > c)
    { 
        return a;
    }    
    else if (b > a && b > c)
    {
        return b;
    }
    else 
    {
        return c;
    }
    
}

int main()
{
    //定义变量
    int a, b, c,max;
    //键入变量
    scanf_s("%d,%d,%d", &a, &b, &c);
 
    max = MAX(a, b, c);
    //输出变量
    printf("max = %d\n",max);
    return 0;
}

4、先比两个数大小,再用较大的数和第三个数比较

程序如下:

#include<stdio.h>



int main()
{
    //定义变量
    int a, b, c,max;
    //键入变量
    scanf_s("%d,%d,%d", &a, &b, &c);
 
    if (a > b )
    {
        max = a;
    }
    else
    {
        max = b;
    }
    if (max < c)
    {
        max = c;
    }

    //输出变量
    printf("max = %d\n",max);
    return 0;
}

5、先将最大值定为其中一值,再与其他两个进行比较

程序如下:

#include<stdio.h>

int main()
{
	//定义变量
	int a, b, c,max;
	//键入变量
	printf("please input a,b,c: \n");
	scanf_s("%d,%d,%d", &a, &b, &c);
	max = a;
	if (max < b)
		max = b;
	if (max < c)
		max = c;

	printf("The largest number is %d\n", max);
	return 0;
}




  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值