【问题标题】:Get smallest and biggest number from Console.WriteLine()从 Console.WriteLine() 获取最小和最大数字
【发布时间】:2016-04-24 19:36:24
【问题描述】:

“练习指南: 首先读取数字的计数,例如在变量 n 中。然后随后用一个 for 循环输入 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[] 需要一个值的错误。是否可以批量解析数组中的所有元素?

【问题讨论】:

  • int.Parse方法。
  • 请检查我的编辑。
  • 您可以使用 Linq 或 for 循环。
  • 你的意思是用for循环来int.解析数组元素?
  • 你已经有一个foreach 循环 - 为什么不对循环中的每个元素进行解析?

标签: c# string parsing


【解决方案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));

这里没有做错误检查,所以输入必须正确

【讨论】:

  • 这行得通。我猜这确实是最简单的方法,因为没有使用 LINQ,而是使用了 Int32.MinValue 和 Int32.MaxValue。
  • 确实... Linq 只是让一切变得更简单(或者您可以使用Math.MaxMath.Min 而不是if's),我只是想编写非常基本的代码。绝对应该对此进行错误检查(使用TryParse而不是Parse,并检查控制台条目),但我坚持你的要求并提供最基本的可能解决方案,因为你似乎正在学习和关注教程:可能会出现错误检查和TryXXX 方法:-)
  • 我可以允许这样做,因为它明确规定只插入整数,我不需要担心识别整数。
  • 我想避免在以后的教程章节中简化编码。谢谢@Jcl
  • @paddy 一旦你了解了基础知识,就很容易从那里开始......记得将你认为对你个人做得更好的答案标记为已接受,所有给出的答案都是完全有效的,并且您可能可以从每个人那里学到一些技巧
【解决方案2】:

要获取用户输入的最小值和最大值,您可以使用 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);
}
...

【讨论】:

  • 本教程目前还没有涵盖 Linq。
  • @paddy 我在示例代码中添加了一些 cmets。 LINQ 是获取最小和最大数字的最简单方法。如果你不想使用它,你可以创建foreach循环并比较所有值以获得最小值和最大值。
  • @paddy 再次检查我的答案。我添加了示例代码以在没有 LINQ 的情况下获取最小值和最大值。
【解决方案3】:

试试

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);
    }
}

【讨论】:

  • 我所遵循的教程还没有达到解释您的解决方案的地步。我宁愿坚持本章所涵盖的基本内容。有没有机会将它与 for 循环结合起来?
  • 这里的列表是干什么用的?
  • 我的意思是,可以用数组之类的东西代替它吗?到目前为止,教程还没有涵盖列表,这就是我问的原因..
  • @paddy 你可以使用ToArray()的方法来做一个数组;)
  • @paddy 是的。这就是内涵
【解决方案4】:
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 和广泛的答案

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-23
    相关资源
    最近更新 更多