c# – 二进制搜索算法出现错误 – 使用未分配的局部变量
发布时间:2020-12-15 08:40:22 所属栏目:百科 来源:网络整理
导读:我正在学习如何从头开始创建二进制搜索算法的教程.但是我收到错误“使用未分配的局部变量’Pivot’”.我是这门语言的新手,以前只尝试过更简单的语言. 我为缺乏内部文档和使用空白区域而道歉. 错误是在使用“//”标记的代码底部附近 这是程序: using System;
我正在学习如何从头开始创建二进制搜索算法的教程.但是我收到错误“使用未分配的局部变量’Pivot’”.我是这门语言的新手,以前只尝试过更简单的语言.
我为缺乏内部文档和使用空白区域而道歉. 错误是在使用“//”标记的代码底部附近 这是程序: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Binary_Search_2 { class Program { static void Main(string[] args) { int[] arr = new int[10]; Random rnd = new Random(); for (int i = 0; i < arr.Length; i++) { arr[i] = rnd.Next(1,10); } Array.Sort(arr); for (int i = 0; i < arr.Length; i++) { Console.Write("{0},",arr[i]); } int Start = 0; int End = arr.Length; int Center = Start + End / 2; int Pivot; while (arr[6] > 0) { while (arr[6] < arr[Center]) { End = Center; Center = (End + Start) / 2; if (Pivot == arr[Center]) { Console.WriteLine("The Index is {0}",arr[Center]); } break; } while (arr[6] > arr[Center]) { Start = Center; Center = (End + Start) / 2; if (Pivot == arr[Center]) //**This is where the error occurs.** { Console.WriteLine("The index is {0}",arr[Center]); } } } } } } 我很抱歉,如果这真的很简单,但我没有任何人直接教我,我没有想法. 解决方法
该错误是由此行引起的:
int Pivot; 在if语句中使用之前,需要设置Pivot的值. 这表示代码中存在错误:您在anif`语句中检查了Pivot的值,但是您从未分配给它.查看教程,找到如下所示的行: Pivot = ... // <<=== some expression here 最有可能的是,当您按照教程操作时,没有将此行输入您的程序. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |