课本例子代码第四章

【例4.1】设计一个控制台应用程序,采用二分查找方法在给定的有序数组a中查找用户输入的值,并提示相应的查找结果。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            double[] a = new double[10]{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
            double k;
            int low = 0, high = 9, mid;
            Console.Write("k:");
            k = double.Parse(Console.ReadLine());
            while(low<high){
                mid = (low + high) / 2;
                if (a[mid] == k)
                {
                    Console.WriteLine("a[{0}]={1}", mid, k);
                    Console.ReadLine();
                    return;
                }
                else if (a[mid] > k) high = mid - 1;
                else low = mid + 1;
            }
            Console.WriteLine("未找到{0}", k);
            Console.ReadLine();
        }
    }
}

【例4.2】设计一个控制台应用程序,输出9行杨辉三角形。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication3
{
    class Program
    {
        const int N = 10;
        static void Main(string[] args)
        {
            int i, j;
            int[,]a=new int[N,N];
            for (i = 1; i < N;i++ ){
                a[i, i] = 1;
                a[i, 1] = 1;
            }

            for (i = 3; i < N;i++ )
                for (j = 2; j <= i-1;j++ )
                    a[i,j]=a[i-1,j-1]+a[i-1,j];

            for (i = 1; i < N; i++) {
                for (j = 1; j <= i; j++) 
                    Console.Write("{0,-3}",a[i,j]);

                Console.WriteLine();
            }
            Console.ReadLine();
           
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41264055/article/details/104913942
今日推荐