【问题标题】:How to increase the array by 1 with each input如何将每个输入的数组增加 1
【发布时间】:2022-01-19 22:37:40
【问题描述】:

我的目标是,在我标记的问题的每个新输入中,数组都会获得一个新输入。 例如:

double[] Test = new double[10];
"give input" | 
int input = int.Parse(Console.ReadLine()) |
Test[0] = input |

再次“提供意见”。只是那个圆圈,每次输入时,“Test [HERE]”都会得到一个新的输入。 (就像你会手动那样)

对不起我的英语不好。英语不是我的母语。

static void Main(string[] args)
        {
            Mittelwert();
        }
        public static void Mittelwert()
        {
            double[] Test = new double[10];
            for (int i = 1; i < 11; i++)
            {
                Console.WriteLine("Geben Sie ihren " + i + " Wert ein");
                int input = int.Parse(Console.ReadLine());

                Test[+1] = input;

            }
            var Average = Enumerable.Average(Test);
            Console.WriteLine("Der Durchschnitt ist " + Average);

        }
    ```

【问题讨论】:

  • Test[+1] 更改为Test[i]
  • @TheBatman 我已经测试过了。我收到错误:“索引超出了数组的反弹范围”
  • 为什么不使用List&lt;T&gt;?当您添加新项目时,它们的大小会自动增加。
  • @s0lid 数组的第一个元素是Test[0],而不是Test[1],数组的最后一个元素是Test[10],而不是Test[11]。你需要改变你的循环。数组是零索引的。括号中的数字应被视为与原点 (0) 的偏移量,而不是元素的位置。
  • @maksymiuk 好主意。谢谢你。我从来没有真正使用过列表。

标签: c# arrays


【解决方案1】:

您可以使用i 作为数组的索引,但请注意C# 数组是从零开始的(即第一个索引是0,第二个索引是1,等等):

for (int i = 0; i < 10; i++)
{
    Console.WriteLine("Geben Sie ihren " + (i +1) + " Wert ein");
    int input = int.Parse(Console.ReadLine());

    Test[i] = input;
}

【讨论】:

    【解决方案2】:

    如果我了解您要做什么,您希望在 collection 上迭代多次,并且一旦迭代器通过 collection 的长度,您本质上想要将新项目附加到末尾。

    对于这个Arrays 不是最佳选择,您想改用List&lt;T&gt;,它会随着您添加新项目而扩大。

        static void Main(string[] args)
        {
            Mittelwert();
        }
        public static void Mittelwert()
        {
            List<double> Test = new List<double> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            for (int i = 1; i < 11; i++)
            {
                Console.WriteLine("Geben Sie ihren " + i + " Wert ein");
                int input = int.Parse(Console.ReadLine());
    
                if (Test.Count < i)
                    Test[i] = input;
                else Test.Add(input);
    
            }
            var Average = Enumerable.Average(Test);
            Console.WriteLine("Der Durchschnitt ist " + Average);
    
        }
    

    【讨论】:

    • 循环仍然需要从 0 开始
    • 我只是逐字复制了他的代码,因为我不想假设用例。在很多情况下,您可能希望从 0 以外的数字开始迭代。
    • 列举一些您正在枚举数组并仅跳过第一个元素的用例
    • 这样的话,你不直接创建容量为11的列表吗?
    • @RufusL 我假设的 11 只是表示迭代次数比集合中的项目多。它可以是任意数字,我们在执行时不一定知道它会小于或大于收集容量。出于此答案的目的,它是一个常数,但仅用于视觉目的。清楚地表明迭代器将超出集合的范围。
    猜你喜欢
    • 1970-01-01
    • 2019-10-21
    • 2017-04-18
    • 1970-01-01
    • 2021-02-16
    • 2015-09-13
    • 2013-12-31
    • 2012-01-01
    • 1970-01-01
    相关资源
    最近更新 更多