快速问题,我发现答案接近这个,但没有任何帮助我.我希望它在小数点后面有4个数字的代码末尾打印一个百分比,当然,使用int工作.但是使用浮点数会给我一个错误.
这段代码:
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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
给出错误:
HW2johnson_pp4.java:8: possible loss of precision
found : float
required: int
float[] numbers = new float[keyboard.nextFloat()];
Run Code Online (Sandbox Code Playgroud)
您无法创建长度为浮点值的浮点数组.也就是说,你不能拥有一个包含2.7个元素的数组.
因此,length参数中的float会变圆,导致精度损失.
你想keyboard.nextInt()在第8行和keyboard.nextFloat()第13行下面.
| 归档时间: |
|
| 查看次数: |
1881 次 |
| 最近记录: |