在分析数据集时,例如人体高度数据或人的体重数据,一个常见的步骤是调整数据。这种调整可以通过正常化到0到1之间的值,或者丢弃异常值来完成。
对于此程序,通过将所有值除以最大值来调整值。输入以一个整数开头,表示后面的浮点值的数目。假设列表总是包含少于20个浮点值.
在小数点之后用两位数字输出每个浮点值,这可以实现如下:
System.out.printf("%.2f", yourValue);例:如果输入是:
5 30.0 50.0 10.0 100.0 65.0
产出如下:
0.30 0.50 0.10 1.00 0.65
5表示列表中有5个浮点值,即30.0、50.0、10.0、100.0和65.0。100.0是列表中最大的值,因此每个值除以100.0。
为了编写简单的代码,请用空格(包括最后一个)来跟踪每个输出值。
到目前为止,这是我的代码:
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
double numElements;
numElements = scnr.nextDouble();
double[] userList = new double[numElements];
int i;
double maxValue;
for (i = 0; i < userList.length; ++i) {
userList[i] = scnr.nextDouble();
}
maxValue = userList[i];
for (i = 0; i < userList.length; ++i) {
if (userList[i] > maxValue) {
maxValue = userList[i];
}
}
for (i = 0; i < userList.length; ++i) {
userList[i] = userList[i] / maxValue;
System.out.print(userList[i] + " ");
System.out.printf("%.2f", userList[i]);
}
}
}我一直得到这个输出。
LabProgram.java:8: error: incompatible types: possible lossy conversion from double to int
double [] userList = new double [numElements];
^
1 error我觉得我的变量搞砸了。我翻阅了我的书,却找不到帮助。有人能帮我一下吗。非常感谢!这对我来说压力很大。
发布于 2022-03-28 16:43:16
特定的错误消息是因为元素的索引和大小必须是int。因此,立即声明和分配:int numElements = scnr.nextInt();
发布于 2022-03-28 17:33:07
更好的编程方法:
示例代码:
public class LabProgram {
public static void main(final String[] args) {
final double[] initialValues = new double[] { 30.0, 50.0, 10.0, 100.0, 65.0 };
final double[] adjustedValues = normalizeValuesByHighest(initialValues);
System.out.println("Adjusted values:");
for (final double d : adjustedValues) {
System.out.printf("%.2f ", Double.valueOf(d));
}
// expected otuput is 0.30 0.50 0.10 1.00 0.65
System.out.println();
System.out.println("All done.");
}
static public double[] normalizeValuesByHighest(final double[] pInitialValues) {
if (pInitialValues == null) throw new IllegalArgumentException("Invalid double[] given!");
if (pInitialValues.length < 1) throw new IllegalArgumentException("double[] given contains no elements!");
// detect valid max value
double tempMaxValue = -Double.MAX_VALUE;
boolean hasValues = false;
for (final double d : pInitialValues) {
if (Double.isNaN(d)) continue;
tempMaxValue = Math.max(tempMaxValue, d);
hasValues = true;
}
if (!hasValues) throw new IllegalArgumentException("double[] given contains no valid elements, only NaNs!");
// create return array
final double maxValue = tempMaxValue; // final from here on
final double[] ret = new double[pInitialValues.length];
for (int i = 0; i < pInitialValues.length; i++) {
ret[i] = pInitialValues[i] / maxValue; // NaN will stay NaN
}
return ret;
}
}输出:
Adjusted values:
0,30 0,50 0,10 1,00 0,65
All done.https://stackoverflow.com/questions/71650714
复制相似问题