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