【问题标题】:problems with a for-loop in C#C#中for循环的问题
【发布时间】:2021-08-22 09:14:33
【问题描述】:

我对 C# 编程非常陌生(到目前为止 2 天),在学习了中级 python 并做了一些小项目之后,我正在努力学习 C#

但是因为我了解python,我发现C#有点混乱,数组总是让我失望,而在python中初始化一个列表就像用空列表声明一个变量x = []一样简单,C#的声明数组的方式令人困惑.

我的问题是,我遇到了一个错误,我用谷歌搜索但一无所获(有一个与我类似的问题,但没有人回答)

我在一个名为 https://codewars.com/ 的网站上正在解决 Katas(问题)[lvl 7(初学者)]

问题说明对于任何输入整数n,我必须返回一个数组,其因子为n 其中n > 1

在python中,代码会是这样的:

def findFactors(n):
    return [x for x in range(2, n) if n % x == 0]

所以我尽我所能将代码转换为:

public class Kata
{
  public static int[] Divisors(int n)
  {
  int counter = 0;
  int[] myNum = {};
  for (int i=2; i == n; i++) {
    int calculate = n % i;
    if (calculate==0) {
      myNum.CopyTo(i, counter);
      counter++;
    }  
  }
    if (myNum.Length == 0) {
      return null;
    }
    else {
      return myNum;
    }
  }
}

我得到的错误是:

src/Solution.cs(10,20): error CS1503: Argument 1: cannot convert from 'int' to 'System.Array'

与 python 中的错误回溯相比,C# 回溯更难理解

那么我该如何解决这个错误呢?

【问题讨论】:

  • counterint,而不是 int[]...
  • 很确定,CopyTo 方法有两个参数,(thing to add, index of where to add inside the list)
  • for循环应该是for (int i=2; i <= n; i++),注意中间部分变了。
  • 没有。 CopyTo 接受一个目标数组和一个索引。请参阅documentation

标签: c# arrays for-loop


【解决方案1】:

要修复您的代码,您需要这样做:

public static int[] Divisors(int n)
{
    int[] myNum = { };
    for (int i = 2; i < n; i++)
    {
        int calculate = n % i;
        if (calculate == 0)
        {
            int[] x = new int[myNum.Length + 1];
            myNum.CopyTo(x, 0);
            x[x.Length - 1] = i;
            myNum = x;
        }
    }
    return myNum;
}

但与您的原始代码直接等效的是:

public static int[] Divisors(int n)
    => Enumerable.Range(2, n - 2).Where(x => n % x == 0).ToArray();

或者使用迭代器:

public static IEnumerable<int> Divisors(int n)
{
    for (int i = 2; i < n; i++)
    {
        if (n % i == 0)
        {
            yield return i;
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-21
    • 2011-07-04
    • 1970-01-01
    • 2020-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多