所以我有这个代码
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返回带有错误信息的字符串,或者在第一次==秒时返回。
答案 0 :(得分:23)
您可以使用内置的Math.Max
Method
答案 1 :(得分: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
{
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;
}
答案 2 :(得分: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
}
答案 3 :(得分: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();
答案 4 :(得分: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);
}