查找一个数字是否在斐波那契范围内
本文关键字:范围内 是否 数字 一个 查找 | 更新日期: 2023-09-27 18:07:28
我打印了一些斐波那契数。现在我想看看我输入的数字是否在这个范围内,如果是,显示它的位置。这是我目前所看到的:
using System;
namespace SomeFibonacciPrimes
{
class SomeFibonacciPrimes
{
static void Main()
{
int first = 0;
int second = 1;
int third = 1;
for (int i = 0; i < 50; i++)
{
third = second;
second = first + second;
first = third;
Console.WriteLine(second);
}
Console.WriteLine("Enter a number to find if it's in Fibonacci range:");
int number = int.Parse(Console.ReadLine());
if (number == second)
{
Console.WriteLine("Your number is within the Fibonacci range.");
}
else
{
Console.WriteLine("Your number is NOT within the Fibonacci range");
}
}
}
}
我不明白为什么如果我输入一个我在范围内看到的数字,If语句会打印else结果?!我认为,在我设法使If语句工作后,位置是for语句中的"I"?
我建议您使用array of integer
或List of integer
来解决此问题:如下所示:
int first = 0;
int second = 1;
int third = 1;
List<int> fibnoList= new List<int>();
for (int i = 0; i < 50; i++)
{
fibnoList.Add(second);
Console.WriteLine(second); //To print the series
third = second;
second = first + second;
first = third;
}
Console.WriteLine("Enter a number to find if it's in Fibonacci range:");
int number = int.Parse(Console.ReadLine());
if (fibnoList.Contains(number))
{
Console.WriteLine("Your number is within the Fibonacci range.");
}
else
{
Console.WriteLine("Your number is NOT within the Fibonacci range");
}
除了使用循环,也许您可以考虑使用
using System;
namespace SomeFibonacciPrimes
{
class SomeFibonacciPrimes
{
static void Main()
{
Console.WriteLine("Enter a number to find if it's in Fibonacci range:");
int number = int.Parse(Console.ReadLine());
if (IsFibonacci(number))
{
Console.WriteLine("Your number is within the Fibonacci range.");
}
else
{
Console.WriteLine("Your number is NOT within the Fibonacci range");
}
}
static bool IsFibonacci(int number)
{
//Uses a closed form solution for the fibonacci number calculation.
//http://en.wikipedia.org/wiki/Fibonacci_number#Closed-form_expression
double fi = (1 + Math.Sqrt(5)) / 2.0; //Golden ratio
int n = (int) Math.Floor(Math.Log(number * Math.Sqrt(5) + 0.5, fi)); //Find's the index (n) of the given number in the fibonacci sequence
int actualFibonacciNumber = (int)Math.Floor(Math.Pow(fi, n) / Math.Sqrt(5) + 0.5); //Finds the actual number corresponding to given index (n)
return actualFibonacciNumber == number;
}
}
}