Frage

I am desperately trying to get the last column of my code to add up all the middle column numbers in a running total.. but it seems to start at 1 already.

Also, a side question: When I input 12.. I get 11 results, due to "y" starting at 1. Is there anyway to fix that in the loop?

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 );
            }
        }
    }
War es hilfreich?

Lösung

to start with start y from zero:

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];
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top