繁体   English   中英

并非所有代码路径都返回值Error

[英]Not all codepaths return a value Error

我正在尝试创建一个简单的程序,找到数组中最大的数字。 我在一个单独的类文件中创建了该方法,然后我只是尝试在主页面中创建该对象,并在我创建的数组上执行该方法。 我知道这与我有关,目前没有返回我的方法的值,但我仍然卡住了。 对于noob问题抱歉,提前谢谢。

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 ,但你的函数永远不会return一个。

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()可能会让您感兴趣,因为它会为您提供一个列表,您的整个列表将从最大数量到最小数量排序

方法签名:

public int FindMax(int[] array)

规定该方法必须返回Int32 但是,它不会返回任何地方。

您需要在方法的末尾添加一个return语句。 也许你的意思是:

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; // <-- Add this
}

我还建议检查以确保array参数至少包含一个元素:

if (array == null || array.Length == 0)
   throw new ArgumentNullException("array");

您永远不会从Class1FindMax方法返回任何内容。 修复它的方法是只添加一个return语句:

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; // add the return statement here.
}

你必须返回一个值

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

              return temp;
    }

    }

    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM