我正在尝试创建一个简单的程序来查找数组中的最大数字。我在一个单独的类文件中创建了该方法,然后试图在主页中创建对象,并在我创建的数组上执行该方法。我知道这与我目前没有在我的方法上返回值有关,但我仍然卡住了。很抱歉这个菜鸟问题,提前致谢。
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;
namespace FindMax
{
class Program
{
public static void Main(string[] args)
{
Class1 MyClass = new Class1();
int[] myArray = new int[] {1, 3, 4, 2, 5, 2, 2, 6, 3344, 223, 35, 5656, 2, 355543, 2222, 2355, 933433};
int y = MyClass.FindMax(myArray);
Console.WriteLine(y);
Console.ReadKey(true);
}}}
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;
namespace FindMax
{
public class Class1
{
public int FindMax(int[] array)
{
int temp = array[0];
for (int i = 0; i < array.Length; i++)
{
if (array[i] > temp)
{
temp = array[i];
}
}}}}
请您参考如下方法:
看起来您在 FindMax 函数的最后一行上方缺少 int 的返回值
实际的错误是说您的方法期望返回一个 int,但您的函数从不返回。
public int FindMax(int[] array)
{
int temp = array[0];
for (int i = 0; i < array.Length; i++)
{
if (array[i] > temp)
{
temp = array[i];
}
}
return temp; //this
}
或者,使用 LINQ,以下将做同样的事情
var largest = array.OrderByDescending(x => x).FirstOrDefault();
正如@MikeChristensen 所指出的,array.Max() 也有效。
var largest = array.OrderByDescending(x => x).ToList() 您可能会感兴趣,因为它会给您一个列表,您的整个列表将从最大到最小排序
