代码之家  ›  专栏  ›  技术社区  ›  James9oo0

如何通知阵列具有特定数据点

  •  0
  • James9oo0  · 技术社区  · 8 年前

    好的,我这里的问题是,我试图创建一个用户输入数组,并通知控制台,如果用户输入数组中有特定的数据点。我知道你可以 看见 数据点在控制台上,但我被要求这样做,我没有问为什么:'D。

    public static void Main()
    {
    
        double [] array= new double [10]
        double temp;
    
        Console.WriteLine("Insert 10 numbers");
    
        for (int i = 0; i < array.Length; i++)
        {
            array[i] = Convert.ToDouble(Console.ReadLine());
        }
    
        Console.WriteLine("What number do you wish to find?");
    
        temp = Convert.ToDouble(Console.ReadLine());
    
        foreach (int i in array)
        {
            if (temp == i)
            {
                Console.WriteLine("The number is in the array.")
                break;
            }
    
            else if (temp != i)
            {
                Console.WriteLine("The number is not part of the array.");
                break;
            }
        }
    }
    

    输出结果是:如果您输入第一个插槽中的数字,它将显示为“数字在数组中”,作为数组一部分的任何其他数字将显示为“数字不是数组的一部分”。如果删除If和Else If代码中的换行符,列表将逐一告诉您该数字是否为数组的一部分。

    如何使它读取整个数组,并告诉我无论什么数字都是数组的一部分?

    笔记 我被要求不要使用LINQ或数组。物体

    1 回复  |  直到 8 年前
        1
  •  1
  •   Dmitrii Bychenko    8 年前

    您不应该检查 temp != i 但是 == 仅在循环内:

      // array is double[] - item is double
      foreach (double item in array) {
        // item found, we shall report and exit the method
        if (item == temp) { // <- dubious: we should check doubles with tolerance
          Console.WriteLine("The number is in the array.");
    
          return; // <- not break
        }
      }
    
      // entire array has been scanned, no item found
      Console.WriteLine("The number is not part of the array.");
    

    如果你不想 return ,但坚持 break :

      bool inTheArray = false;
    
      foreach (double item in array)
        if (item == test) {
          inTheArray = true;
    
          break;
        }   
    
      Console.WriteLine(inTheArray 
        ? "The number is in the array." 
        : "The number is not part of the array.");