简体   繁体   中英

Possible loss of precision error Java

Quick question, I found answers close to this but nothing that helps me. I want it to print out a percentage at the end of the code that has 4 numbers after the decimal point, and of course, using an int work work. But using floats gives me an error.

This code:

import java.util.Scanner;

public class HW2johnson_pp4 {
    public static void main(String args[]) {

        Scanner keyboard = new Scanner(System.in);
        System.out.printf("How many numbers will you enter?\n");
        float[] numbers = new float[keyboard.nextFloat()];

        System.out.printf("Enter " + numbers.length + " integers, one per line:\n");

        for (int i = 0; i <= numbers.length - 1; i++) {
            numbers[i] = keyboard.nextInt();
        }

        float sum = 0;
        for (int i = 0; i <= numbers.length - 1; i++) {
            sum += numbers[i];

        }

        System.out.printf("The sum is " + sum + "\n");

        System.out.printf("The numbers are:\n");

        for (int i = 0; i <= numbers.length - 1; i++) {
            float perc = (numbers[i] / sum);
            float perct = (perc * 100);
            System.out.printf(numbers[i] + " which is " + perct + "%% of the sum.\n");
        }
    }
}

Gives the error:

HW2johnson_pp4.java:8: possible loss of precision
found   : float
required: int
        float[] numbers = new float[keyboard.nextFloat()];

You can't create an array of floats whose length is a floating-point value. That is to say, you can't have an array with 2.7 elements.

So the float within the length parameter is getting rounded, causing a loss of precision.

You wanted keyboard.nextInt() there on line 8, and keyboard.nextFloat() below on line 13.

You cannot initialize an array with floating point values.

float[] a = new float[4]

And not

float[] a = new float[4.0]

So, The problem is here:

float[] numbers = new float[keyboard.nextFloat()];

Use keyboard.nextInt() instead.

You're using keyboard.nextFloat() , which is a float, as the length of the array numbers . The length of an array has to be an int.

Thats because in line 8 you are making a new array, and passing a float as the length. Since all arrays require an integer as an array length, it will convert the float to an integer, and gives an error. You want to pass in an integer value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM