dsorenson
dsorenson

Reputation: 11

Incorrect percentage from integers

My code is giving me 44400.0%. I've messed with it a bunch, but this is the closest I've gotten to the correct answer. I'm only allowed to change things on the line where I've defined the temp array and below. When I try to divide more I lose significant digits, as I need three fours as part of the percentage.

import java.text.DecimalFormat;

public class ArrayElements90OrMore 
{
    public static void main( String [] args ) 
    {
        int [] array = { 91, 82, 73, 94, 35, 96, 90, 89, 65 };
        DecimalFormat percent = new DecimalFormat( "#0.0%" );

        System.out.print( "The elements are " );
        for ( int i = 0; i < array.length; i++ )
            System.out.print( array[i] + " " );
        System.out.println( );

        System.out.println( "The percentage of elements 90 or greater is "
                            + percent.format( percent90OrMore( array ) ) );
    }

    public static int percent90OrMore( int [] temp ) 
    {
        int count = 0;
        for ( int i = 0; i < temp.length; i++ ) {
            if ( temp[i] >= 90 ) {
                count++;
            }
        }

        return  ( count * 1000 ) / ( temp.length );
    }
}

Upvotes: 0

Views: 81

Answers (2)

SMA
SMA

Reputation: 37023

Odd way if you don't want to change method return type is:

System.out.println( "The percentage of elements 90 or greater is "
                        + percent.format( percent90OrMore( array ) * 1000.0d / ( (double) temp.length ) ) );

And change your method as below:

public static int percent90OrMore( int [] temp ) {
    int count = 0;
    for ( int i = 0; i < temp.length; i++ ) {
        if ( temp[i] >= 90 ) {
            count++;
        }
    }

    return count;
}

Upvotes: 0

Eran
Eran

Reputation: 393811

In general, you should multiply by 100 to get the percentage of some fraction :

return  ( count * 100 ) / temp.length;

However, if you are already using percent.format to display the fraction as percentage, you should simply return the fraction :

return  (double) count / temp.length;

Note that in this case percent90OrMore must return a float or a double. Otherwise you'll always get either 0 or 1.

  public static double percent90OrMore (int[] temp)
  {
      int count = 0;
      for ( int i = 0; i < temp.length; i++ )
      {
          if ( temp[i] >= 90 )
          {
              count++;
          }
      }   
      return  (double)count/temp.length;
  }

Upvotes: 3

Related Questions