1

我目前正在编写一个带有人名和 5 个变量的程序。然后使用这 5 个变量,我的任务是找到平均/样本方差。我目前的代码如下:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    namespace ConsoleApplication1
    {
        class Program
        {
        static void Main(string[] args)
        {
            string userName = "";
            string variables = "";
            int[] vars = parseVariableString(variables);
            vars = new int[5];
            int sum = 0;

            Console.Write("Please enter your name: ", userName);
            userName = Console.ReadLine();
            Console.ReadLine();
            Console.Write("Please enter 5 numbers with a space or coma inbetween: ", vars);

            for (int i = 0; i < vars.Length; i++)
            {
                int number = vars[i];
                sum += number;
            }
            float avg = sum/(float)vars.Length;
            float variance = 0;
            for (int i = 0; i < vars.Length; i++)
            {
                int number = vars[i];
                float f = number - avg;
                variance += (float)Math.Pow(f, 2);
            }
            float sv = variance / (vars.Length - 1);

            Console.Write(" Your name is: ", userName);
            Console.ReadLine();
            Console.Write("The average of your numbers is: ", avg);
            Console.ReadLine();
            Console.Write("The sample variance of your numbers is: ", sv);
            Console.ReadKey();
        }

        private static int[] parseVariableString(String variables)
        {
            String[] varArray = variables.Split(' ', ',');
            int[] intArray = new int[varArray.Length];

            for (int i = 0; i < varArray.Length; i++)
            {
                String variable = varArray[i];
                int integer = Convert.ToInt32(variable);
                intArray[i] = integer;
            }
            return intArray;
        }
    }
}

我得到了

输入字符串的格式不正确

错误int integer = Convert.ToInt32(variable);。我不明白为什么我会收到这个错误。我在网上查看了它的含义,很多人说要使用 int.parse 但从我读到的内容中,您会得到这个,因为该变量无法识别出与之关联的值。任何帮助将不胜感激。

4

1 回答 1

6
    string variables = "";
    int[] vars = parseVariableString(variables);

您正在声明一个空字符串,然后尝试将该字符串转换为 int。

private static int[] parseVariableString(String variables)
{
    String[] varArray = variables.Split(' ', ',');
    int[] intArray = new int[varArray.Length];

    for (int i = 0; i < varArray.Length; i++)
    {
        String variable = varArray[i];
        int integer = Convert.ToInt32(variable);
        intArray[i] = integer;
    }
    return intArray;
}

以及当您传入一个空字符串时,没有什么可拆分的,因此您的数组是空的。

于 2013-03-01T18:36:13.383 回答