1

所以我正在研究这个简单的数字预测算法,作为算法和模式识别的入门。它需要一个线性的数字串(在这种情况下为 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
            }
    }
}
4

1 回答 1

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... ;)

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

在调试器下运行程序并单步执行整个过程。这应该告诉您出了什么问题,并让您更好地了解如何解决它。

这将是一个有用的练习,并且比我们只是更正您的所有代码(即使有人确实有时间这样做)对您更有益。

于 2013-04-11T10:29:55.383 回答