我无法摆脱 System.Range.get_Start 错误

I could't get rid of System.Range.get_Start Error

我想创建一个 bool 来控制奇怪的数字,但是当我用 long.Parse 方法填充 "for" 循环时,编译器给了我 System.Range.get_Start 错误。我怎样才能摆脱它?

static void Main(string[] args)
{
    //IsCuriousNum(300);
    Console.ReadKey();
}

static bool IsCuriousNum(long num)
{
    bool isCuriousNum = false;
    long sum = 0;

    string numS = num.ToString();

    for (long i = 0; i < numS.Length; i++)
    {
        char a = (char)long.Parse(numS[i]);
        sum += Factorial(a);
    }

    if (num == sum)
    {
        isCuriousNum = true;
    }

    Console.WriteLine(sum.ToString());

    return isCuriousNum;
}

static long Factorial(long num)
{
    long factorial = 1;

    for (long i = 1; i <= num; i++) factorial *= i;

    return factorial;
}

将循环更改为以下内容:

for (int i = 0; i < numS.Length; i++)
{
    long a = long.Parse(numS[i].ToString());
    sum += Factorial(a);
}

A 在其他答案中提到,您的 for 循环是问题所在。您正在尝试使用不受支持的 long 值 (numS[i]) 为 string 编制索引。仅 int 数据类型支持索引。编译器要求您提供一个实现 long -

的索引
for (long i = 0; i < numS.Length; i++)
{
    char a = (char)long.Parse(numS[i]);
    sum += Factorial(a);
}

而且你说的numlong类型的,但是num的位数最多可以是19位。Int64

Int64 is an immutable value type that represents signed integers with values that range from negative 9,223,372,036,854,775,808 (which is represented by the Int64.MinValue constant) through positive 9,223,372,036,854,775,807 (which is represented by the Int64.MaxValue constant. The .NET Framework also includes an unsigned 64-bit integer value type, UInt64, which represents values that range from 0 to 18,446,744,073,709,551,615.

因此您可以安全地使用 int 来遍历 numnumS 的所有数字。

此外,您可以按如下方式重写 for 循环 -

for (int i = 0; i < numS.Length; i++)
{
    var a = numS[i] - 48;
    //char a = (char)long.Parse(numS[i]);
    sum += Factorial(a);
}

因为 0 的 ASCII 是 48,所以从 char 0 中减去 48 将得到数字 0。