从Console.WriteLine()获取最小和最大的数字

时间:2016-04-24 19:36:24

标签: c# string parsing

"运动指南: 首先读取数字的计数,例如在变量n中。然后输入n个数字,其中一个用于循环。在输入每个新号码时,请将最小最大号码保存在两个变量中,直到此时为止。(...)"

我从C#教程进行练习,但是从一个由未知数量的数字组成的行字符串中提取数字时遇到问题。 到目前为止我有这样的代码:

Console.WriteLine("Type in several Integers:");
string input = System.Console.ReadLine();
string[] splittedLine = input.Split(' ');

foreach(string number in splittedLine)
{
    Console.Write(" " + number);
}

Console.Read();

我应该使用for循环从输入中打印最小和最大的数字。 据我所知,我需要解析splitedLine数组中的数字,使它们是整数,然后比较它们并使用Int32.MaxValueInt32.MinValue。 我坚持"解析"部分代码。

----------更新-----------

当我添加

int[] parsedNumbers = int.Parse(splittedLine[])

我得到splittedLine []需要一个值的错误。是否可以批量解析数组中的所有元素?

4 个答案:

答案 0 :(得分:1)

尝试

int test;
var numbers = 
   from n in input.Split(' ')
   where int.TryParse(n, out test) // Only to test if n is an integer
   select int.Parse(n)
;

int maxValue = numbers.Max();
int minValue = numbers.Min();

没有Linq

int maxValue = int.MinValue;
int minValue = int.MaxValue;

foreach(var s in input.Split(' '))
{
    int number;
    if(int.TryParse(s, out number))
    {
        maxValue = Math.Max(maxValue, number);
        minValue = Math.Min(minValue, number);
    }
}

答案 1 :(得分:1)

要获取用户输入的最小值和最大值,可以使用LINQ。

示例代码:

Console.WriteLine("Type in several Integers:");
string input = System.Console.ReadLine();
List<int> numbers = null;
if(!string.IsNullOrWhiteSpace(input)) // Check if any character has been entered by user
{
    string[] splittedLine = input.Split(' '); // Split entered string
    if(splittedLine != null && splittedLine.Length != 0) // Check if array is not null and has at least one element
    {
        foreach (var item in splittedLine)
        {
            int tmpNumber;
            if(int.TryParse(item, out tmpNumber)) // Parse string to integer with check
            {
                if (numbers == null) numbers = new List<int>(); // If is at least one integer - create list with numbers
                numbers.Add(tmpNumber); // Add number to list of int
            }                            
        }
    }
}
else
{
    // TODO: info for user
}

if(numbers != null) // Check if list of int is not null
{
    Console.WriteLine("Min: {0}", numbers.Min()); // Get min value from numbers using LINQ
    Console.WriteLine("Max: {0}", numbers.Max()); // Get max value from numbers using LINQ
}
else
{
    // TODO: info for user
}
Console.Read();

不使用LINQ的最小值和最大值:

...
if(numbers != null)
{
    var min = numbers[0];
    var max = numbers[0];
    foreach (var item in numbers)
    {
        if (item < min) min = item;
        if (item > max) max = item;
    }
    Console.WriteLine("Min: {0}", min);
    Console.WriteLine("Max: {0}", max);
}
...

答案 2 :(得分:1)

基于您的代码的最基本的解决方案(没有linq或任何东西):

Console.WriteLine("Type in several Integers:");
string input = System.Console.ReadLine();
string[] splittedLine = input.Split(' ');

int max = Int32.MinValue; // initialize the maximum number to the minimum possible values
int min = Int32.MaxValue;  // initialize the minimum number to the maximum possible value
foreach(string number in splittedLine)
{
    int currentNumber = int.Parse(number); // convert the current string element 
                                           // to an integer so we can do comparisons

    if(currentNumber > max)  // Check if it's greater than the last max number
       max = currentNumber;  // if so, the maximum is the current number

    if(currentNumber < min)  // Check if it's lower than the last min number
       min = currentNumber;  // if so, the minium is the current number
}
Console.WriteLine(string.Format("Minimum: {0} Maximum: {1}", min, max));

此处未进行错误检查,因此输入必须正确

答案 3 :(得分:0)

class Program
{
    static public void Main(string[] args)
    {
        // Get input
        Console.WriteLine("Please enter numbers seperated by spaces");
        string input = Console.ReadLine();
        string[] splittedInput = input.Split(' ');

        // Insure numbers are actually inserted
        while (splittedInput.Length <= 0) 
        {
            Console.WriteLine("No numbers inserted. Please enter numbers seperated by spaces");
            splittedInput = input.Split(' ');
        }

        // Try and parse the strings to integers
        // Possible exceptions : ArgumentNullException, FormatException, OverflowException
        // ArgumentNullException shouldn't happen because we ensured we have input and the strings can not be empty
        // FormatException can happen if someone inserts a string that is not in the right format for an integer,
        //      Which is : {0,1}[+\-]{1,}[0-9]
        // OverflowException happens if the integer inserted is either smaller than the lowest possible int
        //      or bigger than the largest possible int
        // We keep the 'i' variable outside for nice error messages, so we can easily understand
        // What number failed to parse
        int[] numbers = new int[splittedInput.Length];
        int i = 0;
        try
        {
            for (; i < numbers.Length; ++i)
            {
                numbers[i] = int.Parse(splittedInput[i]);
            }
        }
        catch (FormatException)
        {
            Console.WriteLine("Failed to parse " + splittedInput[i] + " to an integer");
            return;
        }
        catch (OverflowException)
        {
            Console.WriteLine(splittedInput[i] + " is either bigger the the biggest integer possible (" +
                int.MaxValue + ") or smaller then the lowest integer possible (" + int.MinValue);
            return;
        }

        // Save min and max values as first number
        int minValue = numbers[0], maxValue = numbers[0];

        // Simple logic from here - number lower than min? min becomes numbers, and likewise for max
        for (int index = 1; index < numbers.Length; ++i)
        {
            int currentNumber = numbers[index];
            minValue = minValue > currentNumber ? currentNumber : minValue;
            maxValue = maxValue < currentNumber ? currentNumber : maxValue;
        }

        // Show output
        Console.WriteLine("Max value is : " + maxValue);
        Console.WriteLine("Min value is : " + minValue);
    }
}

这是我在Notepad ++上写的最准确,非linq和广泛的答案