【问题标题】:I can't find where my errors are我找不到我的错误在哪里
【发布时间】:2016-10-27 23:24:45
【问题描述】:

我收到两个错误“无法分配给'C',因为它是'foreach 迭代变量”和“语法错误,预期值”我真的不知道我的错误在哪里?我可以重新审视自己的不足。

int[] numDictionary = new int[] { 5, 5, 5, 7, 7, 7, 9, 7, 9, 9, 9, 1 };

IDictionary<int, int> count = new SortedDictionary<int, int>();    
//count = new SortedDictionary<int, int>();
//int SortedDictionary = count;

foreach (var c in numDictionary)
{
    if (c > 0)
    {
        count[c] = count.[c] + 1;
    }

}
//return count.ToString();
Console.WriteLine(count);
Console.ReadKey();

【问题讨论】:

  • count 是一本字典。 c 是一个整数。无法将 count 分配给 c。此外,正如错误所说,它是一个循环变量。你不能改变它:这是循环的工作。
  • 你创建了两次countcount[c] = c[] +1 应该做什么?也许您应该阅读一些教程。了解类型、数组等。
  • 从您的描述或您发布的代码中,您并不清楚您希望做什么。
  • 我想写一个程序来计算给定的整数数组和每个整数出现的次数。
  • 这是我正在学习的在线课程的一部分,我慢慢发现自己很难通过。我非常不愿意参加在线课程,但这是唯一的编码课程。我现在可以接受。

标签: c#


【解决方案1】:

foreach 循环中,您不能通过索引访问集合的内容。您可以使用您定义的迭代变量(在本例中为var c)直接处理集合项。

Console.WriteLine("Contents of numDictionary: ");
foreach (var c in numDictionary)
{
    Console.Write(c);
}

但是,迭代变量不能被修改 - 它只能被读取。如果要遍历数组并修改内容,请使用for 循环。

int[] numDictionary = new int[] { 5, 5, 5, 7, 7, 7, 9, 7, 9, 9, 9, 1 };

for (int i = 0; i < numDictionary.Length; ++i)
{
    numDictionary[i] = numDictionary[i] + 1;
}

您可以在this Microsoft Development Network article 中找到有关foreach 语句以及它与for 语句的关系的更多信息。

【讨论】:

    猜你喜欢
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-03
    • 1970-01-01
    相关资源
    最近更新 更多