Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Feb 2010
    Posts
    24
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Dividing elements in two diferrent arrays

    I am using an array to store 5 test scores. Then I have another array for the total possible score the test could have. I just need to find out what percent the grade is out of the total possible score.

    Code:
    public class Main {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            int[] grade = new int[5];
            int[] outOf = new int[5];
            int[] percents = new int[5];
            
    
            int total = 0;
            int average;
            int percent;
    
            grade[0] = 70;
            grade[1] = 65;
            grade[2] = 120;
            grade[3] = 150;
            grade[4] = 30;
    
            outOf[0] = 210;
            outOf[1] = 100;
            outOf[2] = 150;
            outOf[3] = 200;
            outOf[4] = 50;
    
            for(int i=0;i<grade.length;i++)
            {
                total += grade[i];
    
            }
    
            average = total / 5;
    
            System.out.println("The total is " + total + "\nThe"
                    + " average is " + average);
            }
            
            for(int j=0;j<grade.length;j++)
            {
               
                
            }
    }

  • #2
    Codeasaurus Rex
    Join Date
    Jun 2008
    Location
    Redmond, WA
    Posts
    659
    Thanks
    31
    Thanked 100 Times in 94 Posts
    You've got everything pretty much set up and good to go. Where you're probably encountering your problem is when it comes to casting. Because the variables are integers, calculating the percentage will reduce to 0.

    You will need to cast to the proper format, then cast to integer. Like so:

    PHP Code:
    percents[j] = (int)( ( (float)grade[j] / (float)outOf[j] ) * 100 );
    System.out.println"Percentage of Grade " " is " percents[j] ); 
    That code would go in that empty for loop of yours.
    Unless otherwise stated, any code posted is most likely untested and may contain syntax errors.
    My posts, comments, code, and suggestions reflect only my personal views.
    Web Portfolio and Code Snippets: http://shanechism.com


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •