小编Jar*_* S.的帖子

当我尝试在列表中找到.IndexOf(a)时,为什么这会返回-1?

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;
            }               
        }
    }
}
}
Run Code Online (Sandbox Code Playgroud)

这是针对项目Euler上的问题25编写的,您需要在Fibonacci序列中找到包含1000位数的第一项的索引.

我检查了一下,应用程序工作直到写入list.IndexOf(a).出于某种原因,它将索引写为-1.

通过在循环中使用带有i ++的整数i(如下所示),我能够解决问题,但我很好奇为什么返回-1而不是索引.

int i …
Run Code Online (Sandbox Code Playgroud)

c# loops for-loop indexof while-loop

2
推荐指数
1
解决办法
85
查看次数

标签 统计

c# ×1

for-loop ×1

indexof ×1

loops ×1

while-loop ×1