栏目分类:
子分类:
返回
文库吧用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
文库吧 > IT > 软件开发 > 后端开发 > C/C++/C#

1002:求三个数最大值 C语言七种写法

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

1002:求三个数最大值 C语言七种写法

1002:求三个数最大值

问题描述:

编写一个程序,输入a、b、c三个值,输出其中最大值。

输入:一行数组,分别为a b c

输出:a b c其中最大的数

样例输入:10 20 30

样例输出:30

提示:C语言程序设计教程(第三版)课后习题1.6

代码:

方法一:假定a为最大值,引入第四个变量,分别与b,c进行比较

#include
int main()
{
    int a, b, c;
    int max = 0;
    scanf("%d %d %d", &a, &b, &c);
    max = a;

    if (max < b)
    { 
        max = b;
    }
    else if (max < c)
    {
        max = c;
    }

    printf("%d", max);
}

方法二:省去第四个变量 直接将变量a作为最大值。

#include
int main()
{
    int a, b, c;
    scanf("%d %d %d", &a, &b, &c);

    if (a < b) 
    {
        a = b;
    }
    if (a < c) 
    {
        a = c;
    }
    printf("%d", a);

    return 0;
}

方法三:直接比较,if else循环嵌套,谁最大输出谁。

#include 

int main()
{
    int a,b,c;
    scanf("%d %d %d", &a, &b, &c);

    if (a > b)
    {
        if (a > c)
        {
            printf("%d", a);
        }
        else
        {
            printf("%d", c);
        }
    }
    else if (b > c)
        {
            printf("%d", b);
        }
        else
        {
            printf("%d", c);
        }

    return 0;
}

方法四:使用&&避免嵌套 与方法三同理。

#include
int main()
{
    int a, b, c;
    scanf("%d %d %d", &a, &b, &c);

    if (a >= b && a >= c) {
        printf("%d" ,a);
    }
    else if (b >= a && b >= c) {
        printf("%d", b);
    }
    else {
        printf("%d", c);
    }

    return 0;
}

方法五:三目运算符(无第四变量)

#include
int main()
{
    int a, b, c;
    scanf("%d %d %d", &a, &b, &c);
    printf("%d", a > b ? (a > c ? a : c) : (b > c ? b : a));
}

方法六:三目运算符(有第四变量)

#include
int main()
{
    int a, b, c;
    int max = 0;
    scanf("%d %d %d", &a, &b, &c);

    max = (a > b) ? a : b;
    max = (max > c) ? max : c;

    printf("%d", max);
}

方法七:三目运算符(a作为第四变量)

#include
int main()
{
    int a, b, c;
    int max = 0;
    scanf("%d %d %d", &a, &b, &c);
    a = (a > b) ? a : b;
    a = (a > c) ? a : c;
    printf("%d", a);
}

解析:

        本题不需要太多数学思维,三个数求最大值即可,但可以利用C语言的变量赋值、循环嵌套以及三目运算符的性质进行多种方法求解,很经典的一道题

转载请注明:文章转载自 www.wk8.com.cn
本文地址:https://www.wk8.com.cn/it/1038903.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 wk8.com.cn

ICP备案号:晋ICP备2021003244-6号