C#基础-数组
2024-10-21 10:16:32
数组定义
定义数组并赋值
int[] scores = { 45, 56, 78, 98, 100 }; //在定义数组时赋值
for(int i = 0; i < scores.Length; i++)
{
Console.WriteLine(scores[i]);
}
定义数组不赋值
string[] stuNames = new string[3];
stuNames[0] = "jame";
stuNames[1] = "max";
stuNames[2] = "joe";
一维数组应用
求数组的和
int[] nums = new int[] { 23, 67, 35, 24, 67 };
int sum = 0;
for(int i = 0; i < nums.Length; i++)
{
sum += nums[i];
}
Console.WriteLine("数字之和为:{0}",sum);
倒序输出
int[] intNums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for(int i = intNums.Length - 1; i >= 0; i--)
{
Console.WriteLine(intNums[i]);
}
求最大值最小值
int[] intN = { 23, 67, 35, 24, 67 };
int max = intN[0];
int min = intN[0];
for (int i = 0; i < intN.Length; i++)
{
if (max < intN[i])
{
max = intN[i];
}
if (min > intN[i])
{
min = intN[i];
}
}
Console.WriteLine("最大值:{0} 最小值:{1}", max, min);
在原有数组中新增
int[] arrS = new int[4] { 12, 13, 14, 15 };
int[] tmp = new int[arrS.Length + 1]; //新增一个数据
for(int i = 0; i < arrS.Length; i++)
{
tmp[i] = arrS[i];
}
Console.WriteLine("输入新增的数据");
int addNum = Convert.ToInt32(Console.ReadLine());
tmp[tmp.Length - 1] = addNum;
arrS = tmp;
Console.WriteLine("输出新的数据:");
for(int i = 0; i < arrS.Length; i++)
{
Console.WriteLine(arrS[i]);
}
新增与删除操作
删除数组中的一个元素
原理:
1.找出删除元素索引
2.索引前的元素直接赋值到临时数组中,索引后的数组在原有数组后索引+1后赋值
int[] arrS = new int[4] { 12, 13, 14, 15 };
Console.WriteLine("请输入你要删除的元素");
int getNum = Convert.ToInt32(Console.ReadLine());
int getIndex = -1;
for(int i = 0; i < arrS.Length; i++)
{
if (getNum == arrS[i])
{
getIndex = i;
break;
}
}
if (getIndex >= 0)
{
int[] tmp = new int[arrS.Length - 1];
for(int i = 0; i < tmp.Length; i++)
{
if (i >= getIndex)
{
tmp[i] = arrS[i + 1];
}
else
{
tmp[i] = arrS[i];
}
}
arrS = tmp;
Console.WriteLine("删除后的数据:");
for(int i = 0; i < arrS.Length; i++)
{
Console.WriteLine(arrS[i]);
}
}
else
{
Console.WriteLine("你所删除的元素不存在!");
}
最新文章
- SSM——(一)
- 通过sqoop来传输mysql/oracle/vertica数据至HBASE
- jQuery的deferred对象详解(转载)
- 【CF】328 D. Super M
- android中定位光标位置
- 对于Web开发来说 8 个最好的跨平台编辑器
- VBS学习日记(一个) 开始了解
- 转:Linux基本命令大全
- OC学习12——字符串、日期、日历
- 【死磕 Spring】—– IOC 之解析Bean:解析 import 标签
- C# ListView 控件和 INotifyPropertyChanged 接口
- React文档(十三)思考React
- 第16月第25天 tableView设置UITableViewStyleGrouped顶部有空余高度
- 2018-2019-2 网络对抗技术 20165227 Exp4 恶意代码分析
- activiti 项目变更控制器
- Rower Bo (高数 + 物理)
- exe程序嵌入Winform窗体
- mysql学习之路_字段类型与属性2
- Java常用排序算法及性能测试集合
- 网站建设中常用的JS代码段落
热门文章
- 用Java创建JMeter变量 - 终极指南
- [Android]Android之四种常见布局
- [NWPU2016][寒假作业][正常版第二组]U
- Http请求数据解释
- (转)io优化
- spring和springmvc是单例还是多例
- MySQL存储过程多条修改语句
- 洛谷 P2983 [USACO10FEB]购买巧克力Chocolate Buying
- 两个div并列居中显示——当display:inline;时,div的宽高不起作用即两个div重叠显示
- 【Python图像特征的音乐序列生成】一个更科学的图片分类参考方法,以及一个看起来很好用的数据集