编写程序以查找输入的非负数序列的最小值

时间:2015-09-20 21:17:30

标签: c#

我在GetMinimumNumber()中的逻辑有问题。我知道我必须将一个数字分配给最小值才能使一切都开始但不知怎的,当我这样做时,我总是以零结束。

namespace Num16
{

    class Program
    {
        static void Main(string[] args)
        {
            int minimum = 0, userInput;

            //call GetUserInput and pass a string prompt to it
            userInput = GetUserInput("Enter the first number or -1 to quit.");

            //determine if the program should procede.
            while (userInput >= 0)
            {
                minimum = GetMinimumNumber(userInput,minimum);
                userInput = GetUserInput("Enter the next number or -1 to quit.");
            }

            Console.WriteLine("The minimum is: {0}",minimum);
        }//end main()

        public static int GetMinimumNumber(int userInput, int minimum)
        {
            int a, b;
            if (userInput < minimum )
            {
                minimum = userInput;
                return minimum;
            }
            else
            {
                return userInput;
            }

        }//end GetMinimumNumber()

        public static int GetUserInput(string prompt)
        {
            Console.WriteLine(prompt);
            return int.Parse (Console.ReadLine());

        }//end GetUserInput()
    }
}

为什么它总是返回0?

1 个答案:

答案 0 :(得分:1)

您可以使用LINQ:

int[] numbers = new int[] {1, 7, -2, 3};
int min = numbers.Min();
Console.WriteLine(min);