数字预测算法中的未知错误

时间:2013-04-11 10:25:47

标签: c# algorithm pattern-matching prediction

所以我正在研究这种简单的数字预测算法,作为算法和模式识别的入口。它需要一个线性的数字串(在这种情况下为14),从2开始,然后上升2到28。

程序通过减去前面的数字来计算每个数字之间的差异。然后检查所有差异是否相同,然后将差异添加到最后一个数字并将其打印到屏幕上。

它工作正常,只是它认为每次差异为0,因此打印最后一个数字28和下一个数字。似乎还有其他这样的问题,除非他们询问如何用非线性序列来做这件事,没有人遇到我的问题。

我已经尝试了所有我能想到的东西,但它仍然无法确定差异。这可能是我很遗憾的事情。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace number_predition_with_constant
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] sequence = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28 }; //all differ by 2. Diff = 2.
            Console.WriteLine(sequence);
            Console.WriteLine("");
            int[] differences = {};
            int legnth = sequence.Length;
            int diff = 0;  //when not given value,  some other instances not recognised 
            int j = 0;
            //find difference between each number.
            for (int i = 0; i == legnth-1; i++)
            {
                j = i + 1;
                diff = sequence[j] - sequence[i];
                differences[i] = diff;
            }
            //Print the difference between each number.
            Console.Write("Difference: ");
            Console.WriteLine(diff);
            //Check all diffs are same. If not the same, print "Error"
            for (int i = 0; i == legnth-1; i++)
            {
                if (differences[i] != differences[i+1])
                {
                    Console.WriteLine("Error");
                }
            }
            //calculate next number and print.
            Console.Write("There are: ");
            Console.Write(legnth);
            Console.WriteLine(" Numbers in the sequence");
            legnth = legnth - 1;
            int next = sequence[legnth] + diff;
            Console.Write("The next Number in the sequence is: ");
            Console.WriteLine(next);
            Console.ReadKey(); //Stop Console from closing till key pressed
            }
    }
}

1 个答案:

答案 0 :(得分:2)

我认为这一行(发生在两个地方)

for (int i = 0; i == legnth-1; i++)

应该是:

for (int i = 0; i <= legnth-1; i++)

还有以下几行:

int[] differences = {};
int legnth = sequence.Length;

应该是:

int legnth = sequence.Length;
int[] differences = new int[legnth];

也可能存在其他问题,但首先要解决这些问题。您可能还希望全局更改legnthlength ...;)

看起来您可能也会遇到一些错误。

在调试器下运行程序,然后单步执行整个过程。这应该告诉你什么是错的,并让你更好地了解如何解决它。

这将是一项非常有用的练习,比我们刚刚更正所有您的代码更有益(即使有任何 有时间这样做) 。