题目:
从键盘输入10个整数,用冒泡或选择法对10个整数进行升序输出。要求带异常处理
代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test1
{
class Program
{
static void Main(string[] args)
{
const int N = 10;
int[] num = new int[N];
int i;
Console.WriteLine("请输入10个数");
try
{
for (i = 0; i < num.Length; i++)
{
num[i] = Convert.ToInt32(Console.ReadLine());
}
//冒泡排序 从小到大
for (i = 0; i < N; i++)
{
for (int j = i + 1; j < N; j++)
{
if (num[j] < num[i])
{
int temp = num[i];
num[i] = num[j];
num[j] = temp;
}
}
}
Console.WriteLine("冒泡配序后的:");
foreach (int temp in num)
Console.Write("{0,-4}", temp);
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine("Exception caught: {0}", e);
}
}
}
}
总结:
1)冒泡法算法的实现,通过两次循环实现了冒泡法。
2) Convert.ToInt32()万能转换器的使用。