5.16 LAB:通过规范化_zybook-Java来调整列表



5.16 LAB:通过规范化调整列表在分析数据集时,例如人的身高或体重数据,一个常见的步骤是调整数据。这种调整可以通过归一化到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.655表示列表中有五个浮点值,即30.0、50.0、10.0、100.0和65.0。100.0是列表中的最大值,因此每个值都除以100.0。

为了简化编码,在每个输出值后面加一个空格,包括最后一个。

我一直对如何在数组和循环中执行浮点值感到困惑,因为在我的书中从未讨论过这一点。

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]; 

我很困惑如何前进,任何帮助都将不胜感激!

只需将numElements的数据类型更改为int,将scanner命令更改为int以及

像这样:

int numElements = scnr.nextInt(); 

你最终弄明白了吗???我有一个解决方案---我不得不做一些调整。我用你的代码作为蓝图,因为我也被卡住了,最后我得到了它对。---干杯

Scanner scnr = new Scanner(System.in);
int numElements; 
numElements = scnr.nextInt(); 
double [] userList = new double [numElements]; 
int i; 
double maxValue; 

for (i = 0; i < userList.length; ++i) { 
userList[i] = scnr.nextDouble(); 
} 

maxValue = userList[0]; 
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.printf("%.2f ", userList[i]);
} 
System.out.println();  
} }

最新更新