Java Array,int重置为0?

时间:2014-04-30 19:57:59

标签: java arrays sum elements

处理用户输入确定数组大小的项目。然后,用户输入值并接收总和。最后,程序向用户显示每个值占总数的百分比。例如,如果数组大小为4且a [0] = 2,a [1] = 1,a [2] = 1,a [3] = 2则显示“2,即总和的33.333% “”1,这是总和的16.666%等。我遇到的问题是在确定了数组和总和之后我试图找到我得到的百分比0.总和是否重置为0,因为它是一个不同的循环?

import java.util.Scanner;

public class CountIntegersPerLine
{
    public static void main(String[] args)
    {
        int elements;
        int arraySize;
        int sum = 0;
        int percentage;
        System.out.println("How many numbers will you enter?");
        Scanner keyboard = new Scanner(System.in);
//Length of array is determined by user input
        arraySize = keyboard.nextInt();
        int[] array = new int[arraySize];
        System.out.println("Enter 4 integers, one per line");
        for (elements = 0; elements < arraySize; elements++)
        {
//Gather user input for elements and add the total value with each iteration
    array[elements] = keyboard.nextInt();
    sum = sum + array[elements];
        }
        System.out.println("The sum is " + sum);
    System.out.println("The numbers are:");
    for (elements = 0; elements < arraySize; elements++)
    {
//Display the percent that each value contributes to the total
    percentage = array[elements] / sum;
    System.out.println(array[elements] + ", which is " + percentage + " of the sum.");
    }
        System.out.println();
}

}

2 个答案:

答案 0 :(得分:1)

当分子小于分母时,整数除法将导致零值。您应将percentage声明为floatdouble

    int percentage;
    ...
    ...
    ...
    percentage = array[elements] / sum;

并且您需要在您的情况下转换除法运算以保留值:

percentage = (double)array[elements] / sum;

答案 1 :(得分:0)

尝试将sum变量声明为double(或float):

double sum = 0.0;

为什么呢?因为在这一行:

percentage = array[elements] / sum;

...您正在执行两个整数之间的分割,并且所有小数都将丢失。您可以验证确实如此,例如尝试:

System.out.println(1/3); // it'll print 0 on the console

这个问题的解决方案是将其中一个分区的操作数作为十进制数,通过声明它们的类型(如上所述)或执行强制转换。或者,这可以在不更改sum的类型的情况下工作:

percentage = array[elements] / ((double)sum);