最小&序列;最大数字

本文关键字:数字 序列 amp 最小 | 更新日期: 2023-09-27 18:08:16

我想让这个程序让我输入一个想要的数字(条目),然后输入一个想要的值到这个条目。它应该写出最大的值(绿色),最小的值(红色),然后是序列的其余部分。在下一行中,最大和最小的位置应该改变(甚至没有为此键入代码)。我做错了什么(特别是在最后一个'for循环')

        int max = int.MinValue;
        int min = int.MaxValue;
        Console.WriteLine("How many numbers do you want to enter ?  ");
        int kolicinaBrojeva = int.Parse(Console.ReadLine());
        int[] niz = new int[kolicinaBrojeva];
        for (int i = 0; i < kolicinaBrojeva; i++)
        {
            Console.WriteLine("Enter {0}. a number:", i + 1);
            niz[i] = int.Parse(Console.ReadLine());
            if (niz[i] > max)
            {
                max = niz[i];
            }
            if (niz[i] < min)
            {
                min = niz[i];
            }
        }
        Console.ForegroundColor = ConsoleColor.Green;
        Console.WriteLine(max + ", ");
        Console.ResetColor();
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine(min + ", ");
        Console.ResetColor();
        for (int i = 1; i >= 0; i--)
        {
            if (niz[i] < max && niz[i] > min)
            {
                Console.Write(niz[i] + ", ");
            }
        }

最小&序列;最大数字

最后一个for循环应该如下所示:

    for (int i = kolicinaBrojeva - 1; i >= 0; i--)
    {
        if (niz[i] < max && niz[i] > min)
        {
            Console.Write(niz[i] + ", ");
        }
    }

您当前的代码将正确读取kolicinaBrojeva数字,但min和max将无法正确设置。没有其他int大于int。MaxValue和类似的,没有其他int小于int. minvalue。您可以这样做:

int max = int.MinValue;
int min = int.MaxValue;

这样,您将得到正确的最小值和最大值,但是,我不确定您在最后一个循环中要做什么。

试试这个

using System;
class Test
{
    static void Main()
    {
        string[] temp = Console.ReadLine().Split();
        int[] numbers = new int[temp.Length];
        for (var i = 0; i < numbers.Length; i++)
             numbers[i] = int.Parse(temp[i]);
        int minIndex = 0;
        int maxIndex = 0;
        for (int i = 0; i < numbers.Length; i++)
        {
            if (numbers[i] < numbers[minIndex])
                minIndex = i;
            if (numbers[i] > numbers[maxIndex])
                maxIndex = i;
        }
        Swap(ref numbers[maxIndex], ref numbers[0]);
        Swap(ref numbers[minIndex], ref numbers[numbers.Length - 1]);
        Print(numbers, ConsoleColor.Green, ConsoleColor.Red);
        Swap(ref numbers[0], ref numbers[numbers.Length - 1]);
        Print(numbers, ConsoleColor.Red, ConsoleColor.Green);
    }
    static void Swap(ref int a, ref int b)
    {
        int temp = a;
        a = b;
        b = temp;
    }
    static void Print(int[] array, ConsoleColor a, ConsoleColor b)
    {
        Console.ForegroundColor = a;
        Console.Write(array[0] + "  ");
        Console.ResetColor();
        for (int i = 1; i < array.Length - 1; i++)
            Console.Write(array[i] + "  ");
        Console.ForegroundColor = b;
        Console.WriteLine(array[array.Length - 1]);
        Console.ResetColor();
    }
}