试图在Fibonacci公式中显示正确的(第n个)值 [英] Trying to show the correct (nth) values in Fibonacci Formula

查看:48
本文介绍了试图在Fibonacci公式中显示正确的(第n个)值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用正确的第n个值正确显示斐波那契公式

其中第n个公式中包含正确的值



一般在此使用的公式是 - > [Fn = F(n-1)+ F(n-2)]

我试图输出公式来显示我是如何得到这样的第n个值 - > [Fn = F( 1-1)+ F(2-2)]

等等。但是我在公式中使用的值并没有计算出正在输出的正确的斐波纳契数。



例如:我知道Fn = F(1-1 )+ F(2-2)= 0,但如果我的输出读数为



Fn = F(1-1)+ F(1-2)= 1

Fn = F(1-1)+ F(1-2)= 1

Fn = F(2-1)+ F(2-2)= 2

Fn = F(3-1)+ F(3-2)= 3



那么这些论坛是不正确的,不等于输出的斐波纳契值。





<前lang =c#> public static int F( int n)
{
// 返回斐波纳契数,0第一,第二#= 1
if (n == 0 || n == 1
< span class =code-keyword> return n;
else
// Fibonacci公式
返回 F(n - 1 )+ F(n - < span class =code-digit> 2 );
}

private void btnStartStop_Click( object sender,EventArgs e)
{
try
{
// 整数表示系列的开始,第一个元素= 0
int i;

/ * 将显示多少个元素。
* Max 20.任何高于20
*的元素都会增加cpu的负载。 40个元素的可能
*但仅限于更快的
*处理器* /

int length = 的Int32 .Parse(txtFibSeriesLength.Text);

// 循环直到所有元素都已处理
< span class =code-keyword> for
(i = Int32 .Parse(txtFibFirst.Text); i < length; i ++)
{
// 在输出中显示结果窗口。 F(i)处理公式并返回Fibonacci int
if (F(i)> 0
txtOutput.Text = txtOutput.Text + Fn = F( + F(i)+ - 1) + F( + F(i)+ - 2)= + F (i)+ Environment.NewLine;
}
}
catch (异常错误) // < span class =code-comment>如果抛出则捕获异常
{
MessageBox.Show(error.Message); // 如果无效字符串或无字符串则抛出错误
};
}

解决方案

输出错误 - 而非写作:

F(n)= F(n - 1)+ F(n - 2)



你写的是:

F(n)= F(F(n) - 1)+ F(F(n) - 2)





您还应该缓存 F(i)的结果,因为您使用的效率很低计算它的方法。



考虑使用 string.Format 使代码更具可读性。

  int  result = F(i); 
if (结果> 0
{
txtOutput.Text = txtOutput.Text + string .Format( F(n)= F({0} -1)+ F({0} -2)= {1},i,result)+ Environment.NewLine;
}





编辑:

根据您删除的评论,你正在寻找这样的东西:

  int 长度; 
if (!int.TryParse(txtLengthOfSeries.Text, out length))
{
MessageBox.Show( 请输入有效长度!);
txtLengthOfSeries.Focus();
return ;
}

int term1,term2 = 1 ,fib = 0 ;
for int i = 0 ; i < length; i ++)
{
term1 = term2;
term2 = fib;
fib = term1 + fib;

if (i < 2
{
txtOutput.Text + = string .Format( F({0})= {1} \ n,i,fib);
}
else
{
txtOutput.Text + = string .Format( F({0})= F({1})+ F({2} )= {3} \ n,i,i - 1 ,i - 2 ,fib);
}
}


嗯......

斐波纳契序列:

 1 1 2 3 5 8 ... 



但是这段代码:

  if (n ==  0  || n ==  1 
return n;



生成序列

 0 1 1 2 3 5 ... 



尝试:

  if (n ==  0  || n ==  1 
return 1 ;





然而,你这样做的效率非常低:你生成大部分序列两次以生成F [4],因为你递归两次在n-1和n-2上。



我不会为此使用递归:一个简单的循环会快得多效率更高!


我通过删除这些选择功能并将其包含在按钮中来修复它:

  int  Term1 =  0 ,Term2 =  1 ,ReturnTerm = < span class =code-digit> 0 ,i; 
for (i = 0 ; i < ; Int32 .Parse(txtLengthOfSeries.Text); i ++)
{
Term1 = Term2; Term2 = ReturnTerm; ReturnTerm = Term1 + ReturnTerm;
txtFibonacciOutput.Text = txtFibonacciOutput.Text + string .Format( F({0})= F({1})+ F({2})= {3},i,Term1,Term2,ReturnTerm)+ Environment.NewLine;
}


Trying to display the Fibonacci formula correctly with the correct nth values
Where nth would contain the correct value in the formula

Generally the formula used in this is -> [Fn = F(n-1) + F(n-2)]
I am trying to output the formula to show how I got the nth value like this ->[Fn = F(1-1) + F(2-2)]
and so on. But the values I used within the formula aren't calculating to the correct fibonacci number that is being output.

For example: I know Fn = F(1-1) + F(2-2) = 0, but if my output reads

Fn = F(1-1) + F(1-2) = 1
Fn = F(1-1) + F(1-2) = 1
Fn = F(2-1) + F(2-2) = 2
Fn = F(3-1) + F(3-2) = 3

Then these forumlas are incorrect and do not equal the fibonacci value thats been output.


public static int F(int n) 
        {
            // Return Fibonacci number, 0 first, second # = 1
            if (n == 0 || n == 1)
                return n; 
            else
                // Fibonacci Formula
                return F(n - 1) + F(n - 2); 
        }

        private void btnStartStop_Click(object sender, EventArgs e)
        {
            try
            {
                // Integer indicates start of Series, first element = 0
                int i;

                /* How many elements will be displayed.
                 * Max 20. Any elements higher than 20
                 * will increase load on cpu. Possible
                 * for 40 elements but only on faster
                 * processors */
                int length = Int32.Parse(txtFibSeriesLength.Text);

                //Loop until all elements have been processed                 
                for ( i= Int32.Parse(txtFibFirst.Text); i < length; i++)
                {
                    // Show results in output window. F(i) processes formula and returns Fibonacci int
                    if (F(i) > 0 )
                        txtOutput.Text = txtOutput.Text + "Fn = F(" + F(i) + "-1) + F(" + F(i) + "-2) = " + F(i) + Environment.NewLine;                       
                }       
            }
            catch (Exception error) // Catch exception if thrown
            {   
                MessageBox.Show(error.Message);// Throw error if invalid string or no string
            };            
        }

解决方案

Your output is wrong - instead of writing:
F(n) = F(n - 1) + F(n - 2)

you're writing:
F(n) = F(F(n) - 1) + F(F(n) - 2)


You should also cache the result of F(i), since you're using such an inefficient way to calculate it.

Consider using string.Format to make your code more readable.

int result = F(i);
if (result > 0)
{
    txtOutput.Text = txtOutput.Text + string.Format("F(n) = F({0}-1) + F({0}-2) = {1}", i, result) + Environment.NewLine;
}



EDIT:
Based on your deleted comment, you're looking for something like this:

int length;
if (!int.TryParse(txtLengthOfSeries.Text, out length))
{
    MessageBox.Show("Please enter a valid length!");
    txtLengthOfSeries.Focus();
    return;
}

int term1, term2 = 1, fib = 0;
for (int i = 0; i < length; i++)
{
    term1 = term2;
    term2 = fib;
    fib = term1 + fib;
    
    if (i < 2)
    {
        txtOutput.Text += string.Format("F({0}) = {1}\n", i, fib);
    }
    else
    {
        txtOutput.Text += string.Format("F({0}) = F({1}) + F({2}) = {3}\n", i, i - 1, i - 2, fib);
    }
}


Um...
Fibonaci sequence:

1 1 2 3 5 8 ...


But this code:

if (n == 0 || n == 1)
    return n;


Generates the sequence

0 1 1 2 3 5 ...


Try:

if (n == 0 || n == 1)
    return 1;



However, the way you are doing it is very inefficient: you generate most of the sequence twice in order to generate F[4], because you recurse twice on n-1 and n-2.

I wouldn't use recursion for this: a simple loop would be a lot quicker and more efficient!


I fixed it by removing theseparate function and just including it in the button down:

int Term1 = 0, Term2 = 1, ReturnTerm = 0, i;
           for (i = 0; i < Int32.Parse(txtLengthOfSeries.Text); i++)
           {
               Term1 = Term2; Term2 = ReturnTerm; ReturnTerm = Term1 + ReturnTerm;
               txtFibonacciOutput.Text = txtFibonacciOutput.Text + string.Format("F({0}) = F({1})+F({2}) = {3}", i,Term1, Term2, ReturnTerm) + Environment.NewLine;
           }


这篇关于试图在Fibonacci公式中显示正确的(第n个)值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆