Go homepage(回首页)
Upload pictures (上传图片)
Write articles (发文字帖)

The author:(作者)qq
published in(发表于) 2014/7/11 9:18:41
C#中一维数组的使用

C#中一维数组的使用

C#中一维数组的使用

当需要存储多个值时,可以使用一维数组,并通过foreach语句或数组的下标将值读出来。 如图1所示,包括5个元素的数组。

* 示例

一维数组的使用

示例将用户输入的一组数存入数组,并进行降序排序,排序后使用foreach遍历数组并将数组中的元素输出。程序代码如下:



图1 存储5个元素的数组结构

Console.WriteLine("请输入一组数:");

for (int i = 0; i < 5; i++)

{

arr[i] = Convert.ToInt32(Console.ReadLine());

}

for (int i = 0; i < 5; ++i)

{

int temp = arr[i];

int j = i;

while ((j > 0) && (arr[j - 1] > temp))

{

arr[j] = arr[j - 1];

--j;

}

arr[j] = temp;

}

Console.WriteLine("排序后结果为:");

本教程来自网站源代码http://www.isstudy.com

foreach (int n in arr)

{

Console.WriteLine("{0}", n);

}

键运行程序,运行结果如图2所示。



图2 一维数组示例运行结果图

说明:foreach语句声明一个迭代变量,它自动获取数组中每个元素的值。它是遍历一个数组的首选方式。如果要以其他方式遍历数组或修改数组中的元素,那么应该采用for语句,因为foreach语句中的迭代变量是数组的每个元素的只读副本。

完整程序代码如下:

★★★★★主程序文件完整程序代码★★★★★

using System;

using System.Collections.Generic;

using System.Text;

namespace _1

{

class ArrayTest

{

static void Main(string[] args)

{

int[] arr = new int[5];

Console.WriteLine("请输入一组数:");

for (int i = 0; i < 5; i++)

{

arr[i] = Convert.ToInt32(Console.ReadLine());

}

for (int i = 0; i < 5; ++i)

{

int temp = arr[i];

int j = i;

while ((j > 0) && (arr[j - 1] > temp))

{

arr[j] = arr[j - 1];

--j;

}

arr[j] = temp;

}

Console.WriteLine("排序后结果为:");

foreach (int n in arr)

{

Console.WriteLine("{0}", n);

}

}

}

}




If you have any requirements, please contact webmaster。(如果有什么要求,请联系站长)





QQ:154298438
QQ:417480759