简体   繁体   English

Java可能丢失精度错误

[英]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. 我希望它在代码的末尾打印出一个百分比,该百分比在小数点后有4个数字,并且当然要使用int作业。 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. 也就是说,您不能拥有包含2.7个元素的数组。

So the float within the length parameter is getting rounded, causing a loss of precision. 因此,length参数中的float会被舍入,从而导致精度损失。

You wanted keyboard.nextInt() there on line 8, and keyboard.nextFloat() below on line 13. 您希望在第8行上找到keyboard.nextFloat() ,并在第13行上下面想要keyboard.nextInt()

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. 请改用keyboard.nextInt()。

You're using keyboard.nextFloat() , which is a float, as the length of the array numbers . 您正在使用keyboard.nextFloat() (它是一个浮点数)作为数组numbers的长度。 The length of an array has to be an int. 数组的长度必须为int。

Thats because in line 8 you are making a new array, and passing a float as the length. 那是因为在第8行中,您正在制作一个新数组,并传递一个float作为长度。 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. 您想传递一个整数值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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