繁体   English   中英

C# 中的 for 循环问题

[英]problems with a for-loop in C#

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

But because me knowing python, I am finding C# a little confusing, arrays always throw me off, while in python initializing a list is as easy as declaring a variable with empty lists x = [] , C#'s way of declaring arrays is confusing.

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

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

问题指出,对于任何输入 integer 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# 回溯更难理解

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

要修复您的代码,您需要执行以下操作:

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;
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM