获得总数?

时间:2013-10-06 21:58:51

标签: java equation-solving

我正在拼命地尝试将我的代码的最后一列添加到运行总计中的所有中间列数...但它似乎已从1开始。

另外,一个侧面问题:当我输入12 ..我得到11个结果,因为“y”从1开始。无论如何要在循环中修复它吗?

import javax.swing.JOptionPane;
public class Project
    {
    public static void main( String[] args )
        {
        String input = JOptionPane.showInputDialog( "How many Fibonacci numbers 
                                                     do you wish to see?" +
                                                     "\n" + "Choose 1-50!");

        int numFib = Integer.parseInt( input );
        int numbers[] = new int[numFib];
        int fibonacci[] = new int[50];

        for( int index = 1; index < numbers.length; index++ )
            {
            numbers[index] = index;
            }
        for( int x = 0; x < numbers.length; x++ )
            {
            if( x == 0 )
                {
                fibonacci[0] = 0;
                }
            if( x == 1 )
                {
                fibonacci[1] = 1;
                }
            if( x > 1 )
                {
                fibonacci[x] = fibonacci[x-2] + fibonacci[x-1];
                }
            }
        System.out.println( "Number" + "\t" + "Fibonacci Number" + "\t" + 
                                              "Running Total of FNs" );
        for( int y = 1; y < numbers.length; y++ )
            { 
            int total = fibonacci[y] + fibonacci[y - 1];

            System.out.println( numbers[y] + "\t" + fibonacci[y - 1] 
                                + "\t" + "\t" + "\t" + total );
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

从零开始y开始:

int total = 0;
for( int y = 0; y < numbers.length; y++ )
{ 
   total += fibonacci[y];

   System.out.println( numbers[y] + "\t" + fibonacci[y] 
                                + "\t" + "\t" + "\t" + total );
}

total -= fibonacci[0] + fibonacci[numbers.length-1];