DevX Home Today's Headlines   Articles Archive   Tip Bank   Forums

1. Registered User
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. ## 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;`

3. Registered User
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
•

 FAQ Latest Articles Java .NET XML Database Enterprise