作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
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;
}
}
}
}
}
这是为 Euler 项目的第 25 题编写的,您需要在其中找到包含 1000 位数字的斐波那契数列中第一项的索引。
我检查了应用程序,直到写入 list.IndexOf(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; //
}
关于c# - 为什么当我尝试在列表中查找 .IndexOf(a) 时返回 -1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34103191/
我是一名优秀的程序员,十分优秀!