C++ 数组(一维数组)

C++ 数组(一维数组)

ZH_qaq

练习比赛号

介绍

数组是一个集合,用于存放相同类型的数据元素。

  • 特点1:数组中的每个数据元素具有相同的数据类型。

  • 特点2:数组占用一段连续的内存空间。

一维数组

一维数组定义方式

注1:数组名的命名规范与变量名命名一致,且数组名不能与变量重名。

注2:数组的下标/索引从 0 0 0 开始。

一维数组定义的3种方式:

  1. 数组名[数组长度]; a[114514]

注:定义数组时,若未给定数组元素的初始值,则必须指定初始数组长度,否则提示错误:“不允许使用不完整的类型”。

  1. 数组名[数组长度] = { 值1,值2 …}; a[114514]={10086, 1919810}

注:数组初始化时,若大括号{ }内的元素个数小于定义的数组长度,则剩余数组元素默认使用 0 填充。

  1. 数组名[] = { 值1,值2 …}; a[]={114514,10086,1919810}

注:定义数组元素初始值时,数组可以不指定初始数组长度。

数组要开大!!!!!

数组的输入输出

#include <bits/stdc++.h>
using namespace std;
int a[1005], n;
int main() {
	cin >> n;
	for(int i = 1; i <= n; i ++) {
		cin >> a[i];
	}
	for(int i = 1; i <= n; i ++) {
		cout << a[i] << " ";
	}
	return 0;
}

P1428 小鱼比可爱

#include <bits/stdc++.h>
using namespace std;
int n, ans = 0, a[105];
int main() {    
	cin >> n;
	for(int i = 1; i <= n; i ++) { // 输入数组
		cin >> a[i];
	}
	for(int i = 1; i <= n; i ++) { // /枚举 n 条鱼
		for(int j = i; j >= 1; j --) { // 从第 i 个位置倒着往前找
			if(a[i] > a [j]) {
				ans ++; // 如果找到比第 i 条鱼丑的,计数器 +1
			}
		}
		cout << ans << " ";
		ans = 0; // 将答案赋值为 0,尽行下一次循环
	}
	return 0;
}

P1427 小鱼的数字游戏

#include <bits/stdc++.h>
using namespace std;
int a[105], b = 1, n = 0;
int main() {
	while(b != 0){ //循环读入,遇零终止
		cin >> b;
		if(b != 0) {
			a [++ n] = b; //读入数据至数组
		}
	}
	for(int i = n; i >= 1; i --) { // 倒序遍历输出
		cout << a[i] << " ";
	}
	return 0;
} 

P1047 校门口的树

#include <bits/stdc++.h>
using namespace std;
int a[10005], l, m, u, v, ans = 0;
int main() {
	cin >> l >> m;
	for(int i = 0; i <= l; i ++) { // 将路上的所有树打上标记,表示这个点没有被访问过
		a[i] = 1;
	}
	for(int i = 0; i <= m - 1; i ++) { // 读入区间的头和尾
		cin >> u >> v;
		for(int j = u; j <= v; j ++) { // 从这个区间的头开始循环,到尾结束
			a[j] = 0; // 标记为访问过
		}
	}
	for(int i = 0; i <= l; i ++) { 
		if (a[i] == 1) { //没被标记过的点说明没有修地铁,树保留
			ans ++;
		} 
	}
	cout << ans;
	return 0;
}

P5727 【深基5.例3】冰雹猜想

#include <bits/stdc++.h>
using namespace std;
int n, a[205], tot = 1;
int main() {
	cin >> n;
	while(n != 1) {
		// 按照题目模拟
		a[tot] = n;
		tot ++ ;//将得到的数记录下来
		if(n % 2 == 0) {
			n = n / 2;
		}
		else {
			n = 3 * n + 1;
		}
		
	}
	a[tot] = 1;
	for(int i = tot; i >= 1; i --) { // 倒序输出
		cout << a[i] << " "; 
	}
	return 0;
}

P5728 【深基5.例5】旗鼓相当的对手

#include <bits/stdc++.h>
using namespace std;
int main() {
	int c[1005], m[1005], e[1005], tot[1005], ans = 0, n;
	cin >> n;
	for(int i = 1; i <= n; i ++) {
		cin >> c[i] >> m[i] >> e[i];
		tot[i] = c[i] + m[i] + e[i]; // 计算总分
	}
	for(int i = 1; i <= n; i ++) {
		for(int j = i + 1; j <= n; j ++) {
			if((abs (c[i]- c[j]) <= 5) && (abs(m[i] - m[j]) <= 5) && (abs(e[i] - e[j]) <= 5) && (abs(tot [i] - tot[j]) <= 10)) {
				ans ++;	
			} // 按要求模拟
		}
	}
	cout << ans;
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值