斐波那契计算 [英] Fibonacci calculation

查看:68
本文介绍了斐波那契计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该程序应该从用户那里获得一个斐波那契数,并且程序将在确定用户输入正数和不小于70的斐波那契数的同时计算该数字.因此,如果用户输入7,它应该打印13.应该使用fibcalc()方法进行计算.尝试编译程序时,出现错误无法将Fibonacci类中的fibcalc方法应用于给定类型: System.out.printf("Fibonacci#%d为%f",num,fibcalc(num,x3)); 和找不到符号" 返回x3; 这是我的代码:

This program is supposed to get a Fibonacci number from the user and the program will calculate what it is while making sure that the user entered a positive number and a number no less than the Fibonacci number 70. So, if the user entered 7, it should print 13. The method fibcalc() is supposed to do the calculations. When I try and compile the program, I get the errors "method fibcalc in class Fibonacci cannot be applied to given types: System.out.printf("Fibonacci #%d is %f", num, fibcalc(num, x3)); and "cannot find symbol" return x3;Here's my code:

import java.util.Scanner;

public class Fibonacci
{
    public static void main ( String args[] ) 
    {
    Scanner input = new Scanner ( System.in );

        int num; 
        double x3 = 0;


           System.out.print("Which Fibonacci number would you like? ");
       num = input.nextInt(); 
           do
       {
        System.out.print("Which Fibonacci number would you like? ");
        num = input.nextInt(); 
    }while(num >= 0 && num <= 70);

    System.out.printf("Fibonacci #%d is %f", num, fibcalc(num, x3));

}


public static double fibcalc(int num) 
{
    int x1 = 0;
    int x2 = 1;

        if (num == 0)

            return 0;

        else if (num == 1)

            return 1;

        else

            for (int x3 = 0; x3 < num; x3++)
                {
                    x3 = x1 + x2;
                    x1 = x2;
                    x2 = x3;
                }
                return x3;

}
  }

我可能还错过了其他问题.我是Java的新手.预先感谢.

There are probably other problems I've missed. I'm pretty new to java. Thanks in advance.

推荐答案

fibcalc()方法只有一个 int 参数,但是您可以使用两个参数.

The fibcalc() method has a single int parameter, but you are calling it with two parameters.

更改呼叫来源

fibcalc(num, x3)

fibcalc(num)

即将该行更改为:

System.out.printf("Fibonacci #%d is %f", num, fibcalc(num));


此外,如果您想要准确的结果数字,请从使用 double 更改为使用


Also, if you want accurate numbers for your results, change from using double to using BigInteger, which can handle arbitrarily large numbers accurately.

这篇关于斐波那契计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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