存储来自循环的用户输入以在另一种方法中进行进一步操作的最佳方法

Best way to store user input from loop for further operations in another method

这只是一个例子,我希望能够在第二种方法中使用第一种方法中数组中的存储值来求算术平均值,问题是我如何访问它?或者数组本身是一个错误的解决方案?

using System;
namespace arithmetic_mean
{
    class Program

    {
        static void Main(string[] args)

        {
            Console.WriteLine("How many decimal numbers do you plan to enter?");
            string userInput = Console.ReadLine();
            int num_user;
            int.TryParse(userInput, out num_user);

            first_method(num_user);
        }

        static void first_method(int num_user)
        {
            string[] newarray = new string[num_user];
            for (int i = 0; i < num_user; i++)
            {
                Console.WriteLine("Enter a decimal number:");
                newarray[i] = Console.ReadLine();
            }
        }

        static void second_method(string newarray)
        {
            Convert.ToDouble(newarray);
            // get arithmetic_mean
        }

    }
}

创建列表 把它们加进去 并将其传递给方法。 最简单、清晰、简单。

我认为最好的方法是制作接受参数和 return 操作结果的小方法。在下面的示例中,您可以看到在 Main 方法中有 3 行代码是高级描述程序应该做什么。从控制台读取数字,然后计算平均值,并将平均值打印到控制台。

ReadNumberFromConsole 之类的方法具有明确定义的名称,因此即使不阅读其代码,您也可以了解它的作用。工作结果是 returned,所以它可以传递给下一个方法。这样您就可以根据需要轻松测试和修改代码。

using System;

namespace ConsoleApp7
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            decimal[] numbers = ReadNumbersFromConsole();
            decimal mean = CalculateMean(numbers);
            PrintMean(mean);
        }

        private static decimal[] ReadNumbersFromConsole()
        {
            string userInput = string.Empty;

            Console.WriteLine("How many decimal numbers do you plan to enter?");
            userInput = Console.ReadLine();
            int numbersLength = int.Parse(userInput);

            decimal[] numbers = new decimal[numbersLength];
            for (int i = 0; i < numbersLength; i++)
            {
                Console.WriteLine("Enter a decimal number:");
                userInput = Console.ReadLine();
                decimal number = decimal.Parse(userInput);
                numbers[i] = number;
            }

            return numbers;
        }

        private static decimal CalculateMean(decimal[] numbers)
        {
            // Do your calculations here
            return 0;
        }

        private static void PrintMean(decimal mean)
        {
            // Example display
            Console.WriteLine($"Calculate mean is {mean}");
        }
    }
}

一般情况下你可以只枚举值而不存储它们(假设你从数据库,你有100亿个),即

  using System.Collections.General;
  using System.Linq;

  ... 

  static IEnumerable<double> first_method(int num_user) {
    // for eaxh user
    for (int i = 0; i < num_user; ++i) {
      // we keep asking until valid value is provided
      while (true) {
        Console.WriteLine($"For user #{i + 1} enter a decimal number: ");

        if (double.TryParse(Console.ReadLine(), out var result)) {
          // we return result and keep on doing for the next user
          // note yield return, not return
          yield return result;

          break;
        }

        Console.WriteNumber("Syntax error. Please, repeat again"); 
      }
    }
  }

然后,无论何时你想要一个集合,你都可以具体化枚举:

  double[] data = first_method(num_user).ToArray();

如果你想计算算术平均值

  static void second_method(int num_user)
  {
     double mean = first_method(num_user).Average();    
      ... 
  }

甚至,没有 second_method

   static void Main(string[] args)
   {
        int num_user; 

        do { // keep asking until correct value provided
            Console.WriteLine("How many decimal numbers do you plan to enter?");
            string userInput = Console.ReadLine();
        } 
        while(!int.TryParse(userInput, out num_user) && num_user > 0);

        double mean = first_method(num_user).Average();  

        Console.WriteLine($"users: {num_user}, mean: {mean}"); 
    }

您的代码在样式和最佳设计实践方面存在很多问题。我不会在这里深入讨论这个问题,只关注这个问题:除了 first_method 之外,我如何使用来自 first_method 的数组?

有几种方法可以在另一种方法中使用一种方法的值。最简单的方法是通过 return 值。我已经将 first_method 重写为 return 数组:

static string[] first_method(int num_user) // The signature changed: void -> string[]
{
    string[] newarray = new string[num_user];
    for (int i = 0; i < num_user; i++)
    {
        Console.WriteLine("Enter a decimal number:");
        newarray[i] = Console.ReadLine();
    }

    return newarray; // Added this line.
}

所以现在您可以在 Main 中使用该数组:

static void Main(string[] args)

{
    Console.WriteLine("How many decimal numbers do you plan to enter?");
    string userInput = Console.ReadLine();
    int num_user;
    int.TryParse(userInput, out num_user);

    string[] inputs = first_method(num_user); // The return value of first_method is now stored.

    // Now it's possible to use the array in second_method:
    foreach(var input in inputs)
        second_method(input);
}

同样,您的代码还有许多其他问题,但您显然是新手。希望在不久的将来看到你越来越好!