C# 返回两个数字中较大值的方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19070403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Method that returns greater value of two numbers
提问by Martin Dzhonov
So I have this code
所以我有这个代码
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
{
// ??????
}
}
is there a way to make GetMax return a string with error message or something when first == second.
有没有办法让 GetMax 在 first == second 时返回带有错误消息或其他内容的字符串。
采纳答案by FreeNickname
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!!!");
}
}
but really I would simply do:
但我真的会简单地做:
public static int GetMax(int first, int second)
{
return first > second ? first : second;
}
回答by Tilak
Since you are returning greater number, as both are same, you can return any number
由于您返回更大的数字,因为两者相同,您可以返回任何数字
public static int GetMax(int first, int second)
{
if (first > second)
{
return first;
}
else if (first < second)
{
return second;
}
else
{
return second;
}
}
You can further simplify it to
您可以进一步简化为
public static int GetMax(int first, int second)
{
return first >second ? first : second; // It will take care of all the 3 scenarios
}
回答by Meikanda Nayanar . I
If possible to use the List type, we can make use of the built in methods Max() and Min() to identify the largest and smallest numbers within a large set of values.
如果可能使用 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();
回答by Chad Richardson
You can use the built in Math.Max
Method
您可以使用内置的Math.Max
方法