如何从我的函数中将计数整数返回到main?

时间:2016-12-21 01:39:47

标签: c# visual-studio parameters parameter-passing

我对编程很新,并试图让这个项目从函数返回一个值到main,但是我在传递数据和格式时有点粗略。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace most_frequent_int
{
    class Program
    {
        static void Main(string[] args)
        {
            mostFreq(new int[] {1,5,2,5,24,6,5});
        }

        static void mostFreq(int[] number)
        {
            int element = 0;
            int count = 0;

            for (int j = 0; j < number.Length; j++)
            {
                int tempElement = number[j];
                int tempCount = 0;

                for (int p = 0; p <number.Length; p++)
                {
                    if (number[p] == tempElement)
                    {
                        tempCount++;
                    }
                    if (tempCount > count)
                        element = tempElement;
                    {
                        count = tempCount;
                    }
                }
            }
            Console.WriteLine("The most frequent element is: " + element + " and appears " + count + " times.");
        }

    }
}

我正在尝试将方法中的值存储在count中并将其返回到main以便在那里再次使用,但我正在努力解决这个问题。 真的很抱歉,如果这是一个完全愚蠢的问题,但任何帮助都表示赞赏。

3 个答案:

答案 0 :(得分:2)

首先将方法的返回类型更改为您想要的:(整数)

static int mostFreq(int[] number)
{
    //...
}

在你的mostFreq方法中,使用return关键字传递你需要返回的值:

static int mostFreq(int[] number)
{
    //...
    return count;
}

然后捕获main中的值并使用它:

static void Main(string[] args)
{
    int count = mostFreq(new int[] {1,5,2,5,24,6,5});
    Console.WriteLine("Count is " + count);
}

答案 1 :(得分:1)

从函数与调用者进行通信的最简单方法可能只是返回值,例如以下示例:

static int return42() {
    return 42;
}

然后,在main

int fortytwo = return42();

换句话说,它需要:

  • 确保函数签名返回实际类型而不是void;
  • 实际上从函数返回所需的值;和
  • 让调用者获取返回值以供以后使用。

不幸的是,您希望返回两个值。虽然你可以返回字符串本身并且只是在main中打印它,但如果你想以其他方式使用其他方面的计数和值,它并不能真正给你提供适应性代码。

毕竟,这是将事物放入函数的主要原因,因此可以从很多地方调用公共代码。

更具适应性的方式可以使用多种选项,例如:

  • 使用元组,它是一个包含多个对象的类;
  • 如果变量属于同一类型,则返回数组;或
  • 在函数中使用out参数作为辅助返回值。

例如,使用最后一个会带来类似的东西(实际代码替换为一些魔术函数调用以用于演示目的):

static void mostFreq(int[] number, [out] int value) {
    value = MagicMostCommonValueInArray();
    return MagicCountOfThatValue();
}

然后,在main

int element;
int count = mostFreq(new int[] {1,5,2,5,24,6,5}, out element);
Console.WriteLine(
    "The most frequent element is: " + element +
    " and appears " + count + " times.");

我的建议是使用该方法而不是返回单个字符串。

答案 2 :(得分:0)

应该是:

<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>