循环时Uint64中的意外值

时间:2019-07-02 13:47:48

标签: c#

我写了一个简短的脚本来计算斐波那契数列,只是为了好玩。使用Uint64,序列应在x=> 18,446,744,073,709,551,616‬时停止。

但是,当序列趋向无穷大时,我得到的东西就非常不同,有时值会减小。

这是我的算法:

static void Main(string[] args)
        {
            bool Error = false;

            UInt64 X = 1;
            UInt64 Y = 1;
            UInt64 Z = 0;

            DateTime Start = DateTime.Now;

            while (!Error)
            {
                try
                {
                    Z = X + Y;

                    Console.Out.WriteLine(Z.ToString("0,0"));

                    X = Y;
                    Y = Z;
                }
                catch
                {
                    Error = true;
                }



            }

            Console.Out.WriteLine("Max value reachd: " + Z.ToString());
            TimeSpan Duration = DateTime.Now - Start;
            Console.Out.WriteLine("This took" + 
            Duration.TotalSeconds.ToString() + " seconds");

            Console.In.ReadLine();

        }

有人可以解释这种行为吗?

这是输出示例:

4,808,835,623,615,708,056

5,982,022,270,976,898,581

10,790,857,894,592,606,637

16,772,880,165,569,505,218

9,116,993,986,452,560,239

7,443,130,078,312,513,841

16,560,124,064,765,074,080

5,556,510,069,368,036,305

3,669,890,060,423,558,769

9,226,400,129,791,595,074

12,896,290,190,215,153,843

3,675,946,246,297,197,301

16,572,236,436,512,351,144

1,801,438,609,099,996,829

18,373,675,045,612,347,973

1,728,369,581,002,793,186

1,655,300,552,905,589,543

3,383,670,133,908,382,729

5,038,970,686,813,972,272

8,422,640,820,722,355,001

13,461,611,507,536,327,273

请注意,当值应该抛出异常时,该值会翻转并继续计算。

0 个答案:

没有答案