返回两个数字中较大值的方法

问题描述 投票:0回答:6

所以我有这个代码

  static void Main(string[] args)
    {
        Console.Write("First Number = ");
        int first = int.Parse(Console.ReadLine());

        Console.Write("Second Number = ");
        int second = int.Parse(Console.ReadLine());

        Console.WriteLine("Greatest of two: " + GetMax(first, second));
    }

    public static int GetMax(int first, int second)
    {
        if (first > second)
        {
            return first;
        }

        else if (first < second)
        {
            return second;
        }
        else
        {
            // ??????
        }
    }

有没有办法让 GetMax 在第一个 == 第二个时返回带有错误消息或其他内容的字符串。

c# methods
6个回答
45
投票

您可以使用内置的

Math.Max
方法


15
投票
static void Main(string[] args)
{
    Console.Write("First Number = ");
    int first = int.Parse(Console.ReadLine());

    Console.Write("Second Number = ");
    int second = int.Parse(Console.ReadLine());

    Console.WriteLine("Greatest of two: " + GetMax(first, second));
}

public static int GetMax(int first, int second)
{
    if (first > second)
    {
        return first;
    }

    else if (first < second)
    {
        return second;
    }
    else
    {
        throw new Exception("Oh no! Don't do that! Don't do that!!!");
    }
}

但实际上我会简单地做:

public static int GetMax(int first, int second)
{
    return first > second ? first : second;
}

4
投票

由于您返回的数字更大,因此两者相同,您可以返回任何数字

public static int GetMax(int first, int second)
{
    if (first > second)
    {
        return first;
    }

    else if (first < second)
    {
        return second;
    }
    else
    {
        return second;
    }
}

您可以进一步简化为

public static int GetMax(int first, int second)
{
  return first >second ? first : second; // It will take care of all the 3 scenarios
}

1
投票

如果可以使用List类型,我们可以利用内置方法Max()和Min()来识别一大组值中的最大和最小数字。

List<int> numbers = new List<int>();
numbers.Add(10);
numbers.Add(30);
numbers.Add(30);
..

int maxItem = numbers.Max();
int minItem = numbers.Min();

0
投票
    static void Main(string[] args)
    {
        Console.Write("First Number: ");
        int number1 = int.Parse(Console.ReadLine());

        Console.Write("Second Number: ");
        int number2 = int.Parse(Console.ReadLine());

        var max = (number1 > number2) ? number1 : number2;
        Console.WriteLine("Greatest Number: " + max);
    }

0
投票

因为你想像这样显示输出

Console.WriteLine("Greatest of two: " + GetMaxString(first, second));

我会让 GetMax 函数返回一个字符串:

public static string GetMaxString(int first, int second)
{
    return (first > second) ? first.ToString() : (second > first) ? second.ToString() : "The two values are equal";
}
© www.soinside.com 2019 - 2024. All rights reserved.