c# – 二进制搜索算法出现错误 – 使用未分配的局部变量

前端之家收集整理的这篇文章主要介绍了c# – 二进制搜索算法出现错误 – 使用未分配的局部变量前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在学习如何从头开始创建二进制搜索算法的教程.但是我收到错误“使用未分配的局部变量’Pivot’”.我是这门语言的新手,以前只尝试过更简单的语言.

我为缺乏内部文档和使用空白区域而道歉.

错误是在使用“//”标记代码底部附近

这是程序:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace Binary_Search_2
  7. {
  8. class Program
  9. {
  10. static void Main(string[] args)
  11. {
  12. int[] arr = new int[10];
  13.  
  14. Random rnd = new Random();
  15.  
  16. for (int i = 0; i < arr.Length; i++)
  17. {
  18. arr[i] = rnd.Next(1,10);
  19. }
  20.  
  21. Array.Sort(arr);
  22. for (int i = 0; i < arr.Length; i++)
  23. {
  24. Console.Write("{0},",arr[i]);
  25. }
  26. int Start = 0;
  27. int End = arr.Length;
  28. int Center = Start + End / 2;
  29.  
  30. int Pivot;
  31.  
  32. while (arr[6] > 0)
  33. {
  34. while (arr[6] < arr[Center])
  35. {
  36. End = Center;
  37. Center = (End + Start) / 2;
  38. if (Pivot == arr[Center])
  39. {
  40. Console.WriteLine("The Index is {0}",arr[Center]);
  41. }
  42. break;
  43. }
  44.  
  45. while (arr[6] > arr[Center])
  46. {
  47. Start = Center;
  48. Center = (End + Start) / 2;
  49. if (Pivot == arr[Center]) //**This is where the error occurs.**
  50. {
  51. Console.WriteLine("The index is {0}",arr[Center]);
  52. }
  53. }
  54. }
  55. }
  56. }
  57. }

我很抱歉,如果这真的很简单,但我没有任何人直接教我,我没有想法.

解决方法

错误是由此行引起的:
  1. int Pivot;

在if语句中使用之前,需要设置Pivot的值.

这表示代码中存在错误:您在anif`语句中检查了Pivot的值,但是您从未分配给它.查看教程,找到如下所示的行:

  1. Pivot = ... // <<=== some expression here

最有可能的是,当您按照教程操作时,没有将此行输入您的程序.

猜你在找的C#相关文章