Find minimum and maximum number from array, minimum is always 0

后端 未结 5 1668
春和景丽
春和景丽 2021-01-12 06:26

The program first asks the user for the number of elements to be stored in the array, then asks for the numbers.

This is my code

    static void Main         


        
相关标签:
5条回答
  • 2021-01-12 06:36

    This code will help you in very simple way without adding any loops and conditions

    int[] arr={1,1,2,4,5,1,2,1};
    Array.Sort(arr);
    Console.WriteLine("Min no: "+arr[0]);
    Console.WriteLine("Max no: "+arr[arr.Length-1]);
    
    0 讨论(0)
  • 2021-01-12 06:37
            for (int i = 0; i < vector.GetLength(0); i++)
            {
                if (i == 0)
                {
                    VectorMinMax[1]= vector[i];
                    VectorMinMax[0]= vector[i];
                }
                else {
                    if (VectorMinMax[1] > vector[i]) VectorMinMax[1] = vector[i];
                    if (VectorMinMax[0] < vector[i]) VectorMinMax[0] = vector[i];
                }
    
            }
    
    0 讨论(0)
  • 2021-01-12 06:42

    You are initializing min to 0.

    Try following

    int min = Int32.MaxValue;
    

    Also In case you are accepting negative values as input, you should initialize max to minimum integer value.

    int max = Int32.MinValue;
    
    0 讨论(0)
  • 2021-01-12 06:56

    Besides on your problem, you can use Enumerable.Min and Enumerable.Max methods like;

    int[] numbers = new int[]{1, 2, 3 ,4};
    Console.WriteLine(numbers.Min()); //1
    Console.WriteLine(numbers.Max()); //4
    

    Don't forget to add System.Linq namespace.

    0 讨论(0)
  • 2021-01-12 06:58

    Your issue is that you're initializing min and max to numbers[0] before numbers is populated, so they're both getting set to zero. This is wrong both for min (in case all your numbers are positive) and for max (in case all your numbers are negative).

    If you move the block

    int min = numbers[0];
    int max = numbers[0];
    

    to after the block

    for (int i = 0; i < n; i++)
    {
        Console.Write("Enter number {0}:  ", i+1);
        numbers[i] = Convert.ToInt32(Console.ReadLine());
    }
    

    then min and max will both be initialized to the first input number, which is fine. In fact you can then restrict your for loop to just check the subsequent numbers:

    for (int i = 1; i < n; i++)
        ....
    

    Just make sure the user's value of n is greater than zero!

    0 讨论(0)
提交回复
热议问题