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;
}