打印斐波纳契数

时间:2013-04-09 07:32:16

标签: java numbers fibonacci

我的程序应根据用户输入的内容输出斐波纳契数(例如,如果他们输入7,程序将输出13)。这部分有效。我遇到问题的部分是程序检查以确保用户输入的数字是正数且小于或等于70.它应该再次询问用户输入,而是输出“Fibonacci#-1”是0“并停止。这是我的代码:

import java.util.Scanner;

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

    int sum = 0;
    int num;
    int f1 = 0, f2 = 0, f3 = 1;

    System.out.print("Which Fibonacci number would you like? ");
    num = input.nextInt(); 

    if (num == 0)
    return 0;

    else if (num == 1)
    return 1;

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

        for(int i = 1; i <= num; i++)
        {
                f1 = f2;
                f2 = f3;
                f3 = f1 + f2;
        }
        System.out.printf("Fibonacci #%d is %d\n",num, f2);
}
}

2 个答案:

答案 0 :(得分:0)

使用它可能会解决您的问题

if(num<0 || num>70)
{
    //ask a number again
}
else
{
    //calculate
}

or use this

if( 0 < num < 71 )
{
    //calculate
}
else
{
     //ask for a valid number
}

答案 1 :(得分:0)

我明白了。

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