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

c++数组 day1数组定义方法,小猪称体重案例(三种思路)

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

c++数组 day1数组定义方法,小猪称体重案例(三种思路)

1,数组定义方法

1.数据类型  数组名[数组长度]                           int  arr[5]

2.数据类型  数组名[数组长度] ={值1,值2.........}          int arr[8] = {1,2,3,4,5,6,6,7} ///注意:数组从0开始数,如果值没填写完,会用0 填充

3.数据类型  数组名[] ={值1,值2.........}                            int arr[] = {1,2,3,4,5,6,6,7}

数据类型必须都相同,比如整型,浮点型

2,例题 小猪称体重

8只小猪找出体重最大的那只

我自己的代码

#include 
#include 
#include  // 控制符
#include 
using namespace std;

  int main()
{
    int arr[8] = {1,23,3,65,5,6,9,7};
    int max = 0;int i = 0;  // max只代表最大 i用来记顺序
    while(i < 8)            //for也可以用
    {
        int a = arr[i];int b = arr[i+1];
        if(max <= a && max <= b)
            {
                if(a > b)
                {
                    max = a;
                }
                else if(a < b)
                {
                    max = b;

                }
            }
            else if(max <= a && max >= b)
            {
                max = a;
            }
            else if(max >= a && max <= b)
            {
                max = b;
            }
        i++;
    }

    cout << max << endl;
        system("pause");

      return 0;

}

由此总结,设一个max与各个数作比较,max只需与一个数作比较即可,数组内的数不需要相互比较

int main()
{
    int arr[8] = {1,23,3,65,5,6,9,7};
    int max = 0;
    for(int j=0;j<8;j++)
    {
        if(max > arr[j])
        {
            max = max;
        }
        else if(max < arr[j])
        {
            max = arr[j];
        }
    }
    cout << max << endl;
        system("pause");

      return 0;

}

代码简洁许多,还可以将if语句用三目运算符优化

int main()
{
    int arr[8] = {1,23,3,65,5,6,9,7};
    int max = 0;
    for(int j=0;j<8;j++)
    {
        max = (arr[j] > max ? arr[j]:max);  //直接三目运算符

    }
    cout << max << endl;
        system("pause");

      return 0;

}

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

版权所有 (c)2021-2022 MSHXW.COM

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