这里的代码很好
import java.util.Scanner;
import java.util.*;
public class ClosesttoAvg{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("input no. elements and then the elements to find
closest to avg");
double size = sc.nextInt(), load = 0;
double array[] = new double[(int)size];
//sort all the no.s into an array and add them all up into load
for(int i = 0; i<size; i++){
array[i] = sc.nextDouble();
load = load + array[i];
}
System.out.println(load);
double avg = load/size, record = size, answer = 0;
//record keeps the smallest distance, answer stores the closest no.,
//problem is located here
这是我遇到问题的地方,但由于某些原因它没有保存正确的变量
for(int i = 0; i<size; i++){
double dist = Math.abs(array[i]-avg);
if(dist < record){
answer = array[i];
}
}
System.out.println(answer);
}
}
答案 0 :(得分:2)
我认为你也应该更新record
。目前,它总是size
,这就是为什么answer
可以被覆盖的原因。
在if
in循环中添加record = dist;
答案 1 :(得分:0)
你检查当前元素是否比平均值更接近平均值,但如果它实际上更接近,你不能将距离保存为最小值,接下来要使用它,你需要:
for(int i = 0; i<size; i++){
double dist = Math.abs(array[i]-avg);
if(dist < record){
answer = array[i];
record = dist; //<---
}
}
答案 2 :(得分:0)
等等,你的答案必须尽量减少!! 所以保持答案变量最大。
answer=Double.MAX_VALUE
for(int i = 0; i<size; i++){
double dist = Math.abs(array[i]-avg);
if(dist < record){
answer = array[i];
record=answer;
}
}
System.out.println(answer);
}
}