课本例子代码第四章
【例4.1】設(shè)計一個控制臺應(yīng)用程序,采用二分查找方法在給定的有序數(shù)組a中查找用戶輸入的值,并提示相應(yīng)的查找結(jié)果。
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】設(shè)計一個控制臺應(yīng)用程序,輸出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();}} }總結(jié)
- 上一篇: if语句(四)
- 下一篇: C---编写程序:求出1~1000之间能