dumbfounded.


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 3 of 3

Thread: dumbfounded.

  1. #1
    Join Date
    Jan 2005
    Posts
    3

    dumbfounded.

    Im trying tog et this simple program to output the percentage of elements in an array but, cannot figure it out for the life of me. I know its something really freaking obvious... but, WHAT IS IT?? ITS KILLING ME!!!! ARRGGGGGGGGGGGGG!!!!!!!!

    =)

    Thanks to whoever can fill me in.

    CODE:

    import java.util.*;

    public class ArrayDemo {

    public static void main(String[] args) {

    Scanner keyboard = new Scanner(System.in);
    System.out.println("How many numbers will you enter?");
    int amountOfIntegers = keyboard.nextInt();

    int[] a = new int[amountOfIntegers];

    int index, sum;
    sum = 0;

    System.out.println("Enter " + a.length + " integers, one per line: ");

    for(index = 0; index < a.length; index++) {
    a[index] = keyboard.nextInt();
    sum = sum + a[index];
    }

    System.out.println("The sum is " + sum + ".");
    System.out.println("The numbers are:");

    double percent;

    for(index = 0; index < a.length; index++) {
    percent = (a[index]/sum) * 100;
    System.out.println(a[index] + " " + percent + "% of the sum.\n");
    }
    }
    }

    OUTPUT:

    How many numbers will you enter?
    5
    Enter 5 integers, one per line:
    1
    2
    3
    4
    5
    The sum is 15.
    The numbers are:
    1 0.0% of the sum.

    2 0.0% of the sum.

    3 0.0% of the sum.

    4 0.0% of the sum.

    5 0.0% of the sum.

  2. #2
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560

    I think this is where it happends:

    Code:
    percent = (a[index]/sum) * 100;
    You should typcast the factors to double, or else the result of the division
    inside the parenthesis is truncated, i.e. it looses its decimals, and they
    are all it's got. As it is, a single integer factor is all it takes to, - solong decimals...
    Code:
    percent = ((double)a[index]/(double)sum) * 100.0d;
    eschew obfuscation

  3. #3
    Join Date
    Jan 2005
    Posts
    3
    thanks bro, I thought that for a second but, didn't try it out.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center