gpt4 book ai didi

c# - 我无法摆脱System.Range.get_Start错误

转载 作者:行者123 更新时间:2023-12-02 10:57:39 25 4
gpt4 key购买 nike

我想创建一个控制奇数的 bool(boolean) ,但是当我用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循环是问题所在。您正在尝试使用不支持的string值(long)为numS[i]编制索引。仅在int数据类型上支持索引。编译器要求您提供一种通过long进行索引的实现-

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

就像您说的 num属于 long一样, 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。

关于c# - 我无法摆脱System.Range.get_Start错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57019287/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com