上一篇一维数组入门博客:一维数组c++ 小白从零教程,超有用!
定义一维数组:
方法1:
例:
int a[5]={4,5,1,2,3};
for (int i=0;i<=4;i++)
{
cout<<a[i]<<" "
}
举个栗子:
#include <bits/stdc++.h>
int year,month,day,s=0;
using namespace std;
int main() {
int a[13]= {0,31,28,31,30,31,30,31,31,30,31,30,31};
cin >> year>>month>>day;
for(int i =0; i<month; i++) {
s+=a[i];
}
s+=day;
if(year%4==0 && year%100!=0|| year%400 ==0) {
if(month>2) {
s+=1;
}
}
cout << s<<endl;
return 0;
}
切记:
数组初始化小工具:
memset(a,0,sizeof(a));
前面加上include <cstring>头文件;
给数组a[5]全附上0;
数字的比特位为32位。
1byte=8bit
sizeof可以获取任何数字占的字节数;
一个栗子:
cout<<sizeof(int)<<endl;
sizeof会给每一个比特位赋上数;
栗如:memset(a,1,sizeof(a));
给每一个比特位赋上1;
这一点注意区分!!!
方法2:
上题:
NO.1:
查找数组中的最大值、最小值
时间限制:1.000s
内存限制:128MB
题目描述
从键盘上读入n个整数,从这n个整数中找出最大值和最小值,以及最大值和最小值的位置。
输入格式
第一行一个整数n(n<100);
第二行n个以空格相隔的整数(每个数在[1,1000])。
输出格式
第一行最大值和最大值的位置,它们之间以空格相隔;
第二行最小值和最小值的位置,它们之间以空格相隔;
样例输入
5
5 3 6 2 4
样例输出
6 3
2 4
LOOK:答案在这里:
#include <bits/stdc++.h>
using namespace std;
int main() {
int n,a[1100],max_1=-1000,maxw=0,min_1=1000,minw=0,sum=0;
cin>>n;
for (int i=1; i<=n; i++) {
sum+=1;
cin>>a[i];
if(a[i]>max_1) {
max_1=a[i];
maxw=sum;
}
if(a[i]<min_1) {
min_1=a[i];
minw=sum;
}
}
cout<<max_1<<" "<<maxw<<endl<<min_1<<" "<<minw;
return 0;
}
NO.2:
查找“支撑数”
时间限制:1.000s
内存限制:128MB
题目描述
在已知一组整数中,有这样一种数非常怪,它们不在第一个,也不在最后一个,而且刚好都比左边和右边相邻的数大,你能找到它们吗?
输入格式
第一行为整数m,表示输入的整数个数。( 3<= m <=100 ) 第二行为m个整数。
输出格式
若干个支撑数,每行一个。
样例输入
14
1 3 2 4 1 5 3 9 7 10 8 23 85 43
样例输出
3
4
5
9
10
85
上代码:
#include <bits/stdc++.h>
using namespace std;
int main() {
int m,a[100],sum=0;
cin>>m;
for(int i=0; i<m; i++) {
cin>>a[i];
}
for(int k=1; k<m-1; k++) {
if(a[k]>a[k-1]&&a[k]>a[k+1]) {
cout<<a[k]<<endl;
sum++;
}
}
return 0;
}
不过,数组还有一种情况:
数组越界
数组越界,就是你没有赋给数组一定数量的值,而代码却要输出许多数量的值。
栗子:
#include <iostream>
#include<cstring>
using namespace std;
int a[5]= {1,2,3,4,5};//数组赋值
int main() {
for(int i=0; i<=100; i++) { //for循环想要输出数组中的100个数
cout << a[i]<<endl;
}
return 0;
}
可以看出,代码只给数组赋了5个元素,而 for循环想要输出数组中的100个数,这显然是不正确的,那么多出来的95个元素会输出什么呢?
下图:
那剩下的95个数是:
1
2
3
4
5
0
0
0
4659472
0
0
0
-1
-1
0
0
255
0
0
0
2
0
0
0
-1
0
0
0
24
-149
104
1
0
14
0
0
53
-1074
971
1
0
14
0
0
64
-16445
16320
1
0
14
0
0
4881024
0
0
0
4299632
0
4299648
0
4300352
0
4300272
0
1
0
0
0
4774784
0
0
0
4778880
0
0
0
4778880
0
0
0
4774784
0
0
0
4774784
0
0
0
4774784
0
0
0
4774784
0
0
0
4774784
0
0
0
4778976
显然是乱码。。。。。。
好了,本篇文章就到这里了喜欢的朋友可以点赞+关注哦!
作者简介:王玉镇 ,一个爱编程的初一学生,热爱c++,Python,Minecraft编程。对Unity 3D感兴趣。喜欢制作各种小游戏。关注我,在学习编程的路上,我们共同前进!