为什么当我尝试查找时返回 -1 .列表中的 IndexOf(a)
本文关键字:列表 IndexOf 返回 查找 为什么 | 更新日期: 2023-09-27 18:25:41
using System;
using System.Collections.Generic;
using System.Numerics;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int charCount = 0;
BigInteger a = 0;
BigInteger b = 1;
List<BigInteger> list = new List<BigInteger>();
while(0 != 1)
{
list.Add(a);
BigInteger c = a; //
a = b; // this is the Fibonacci sequence
b = a + c; //
charCount = a.ToString().Length;
if (charCount >= 1000)
{
Console.WriteLine(list.IndexOf(a));
break;
}
}
}
}
}
这是为欧拉项目的问题 25 编写的,您需要在其中找到包含 1000 位数字的斐波那契数列中第一个项的索引。
我检查了一下,应用程序一直工作到写清单。索引(a(.出于某种原因,它将索引写入 -1。
通过在循环中使用带有 i++ 的整数 i(如下所示(,我能够解决问题,但我很好奇为什么返回 -1 而不是索引。
int i = 0;
int charCount = 0;
BigInteger a = 0;
BigInteger b = 1;
while(0 != 1)
{
i++;
BigInteger c = a;
a = b;
b = a + c;
charCount = a.ToString().Length;
string thing = a.ToString();
if (charCount >= 1000)
{
Console.WriteLine(i);
break;
}
}
list.IndexOf(a) // returns -1 if 'a' could not be fount in 'list'
请注意,您在将其添加到列表后更改了"A",因此当您使用 index of 时,它已经是另一个值。这样它将工作:
while(0 != 1)
{
list.Add(a);
charCount = a.ToString().Length;
if (charCount >= 1000)
{
Console.WriteLine(list.IndexOf(a));
break;
}
BigInteger c = a; //
a = b; // this is the Fibonacci sequence
b = a + c; //
}