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 <iostream>
#include <cmath>
#include <iomanip> // 控制符
#include <ctime>
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;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值