天天看點

c#數組的應用

1 .編寫一個程式,該程式将随機生成的10個數(20-80)放入數組中,找出其中最大數及其下标。

<span style="font-family:SimSun;font-size:18px;">代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 随?機¨²數ºy數ºy組Á¨¦
{
    class Program
    {
        static void Main(string[] args)
        {
            int i ;
            int []a = new int[10];
            int max = a[0];
            int max_i = 0;
            Random run =new Random();
            for (i = 0; i < a.Length; i++)
            {
                a[i] = run.Next(20, 80);
            }
            for (i = 0; i < a.Length; i++)
            {
                Console.WriteLine("\t"+a[i]);
            }
            for (i = 0; i < a.Length; i++)
            {
                if (max < a[i])
                {
                    max = a[i];
                    max_i = i;
                }
            }
            Console.WriteLine("最大值:\t"+max);
            Console.WriteLine("最大值下标\t"+ max_i);
            Console.ReadLine();
        }
    }
}</span>
           

運作結果:

c#數組的應用

2.改寫上述程式,或自程式設計式,實作将其中最大的數與第一個數對換,最小的數與最後一個數對換。

代碼如下:

<span style="font-family:SimSun;font-size:18px;">using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 随?機ú數簓數簓組哩?
{
    class Program
    {
        static void Main(string[] args)
        {
            int max_i = 0;
            int min_i = 0;
            int i, temp, tempi;
            int[] a = new int[10];
            int max = a[0];
            int min = a[9];
            Random run = new Random();
            for (i = 0; i < a.Length; i++)
            {
                a[i] = run.Next(20, 80);
            }
            Console.WriteLine("未′經-交?換?的?數簓組哩?:阰");
            for (i = 0; i < a.Length; i++)
            {
                Console.Write("  " + a[i]);
            }
            Console.WriteLine();

            for (i = 0; i < a.Length; i++)
            {
                if (max < a[i])
                {
                    max = a[i];
                    max_i = i;
                }
                temp = a[0];
                a[0] = a[max_i];
                a[max_i] = temp;
            }
           
            Console.WriteLine("經-過y交?換?的?數簓組哩?:阰");
            for (i = 0; i < a.Length; i++)
            {
                Console.Write("  " + a[i]);
            }
            Console.WriteLine();
            Console.WriteLine("最?大洙?值μ:阰\t" + a[0]);
            Console.ReadLine();
        }
    }
}</span>
           

運作結果:

c#數組的應用