2017-08-16 108 views
0
  1. 這樣做的目的是找到最近沒有。出輸入編號S的編號S
  2. 出於某種原因的總和的平均它未輸出正確的答案附近的決賽圈。
  3. 下這裏的代碼是罰款找到一個最接近java平均值的int值?

    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 
    
  4. 這裏是我有問題,但是,由於某種原因,它不保存正確的變量

    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

這是正確的代碼? ^^因爲'load'不會單獨編譯,你錯過了一些字符,並解釋說,這不是給人很好的答案,提供樣品的輸入和給出代碼 – azro

+0

的輸出下面是一些[免費調試諮詢】(HTTPS: //ericlippert.com/2014/03/05/how-to-debug-small-programs/) –

+0

只是editted它在那裏,忘了縮進代碼的一部分 –

回答

2

我認爲你也應更新record。現在它總是size,這就是爲什麼你answer可以被覆蓋。

在循環if添加record = dist;

+0

謝謝我沒有看到的錯誤。 –

+0

我認爲你應該初始化'一些價值,在它第一次迭代變化首先'dist' record'。要做到這一點,你可以用'布爾flag'或設置'record'到'-1'和循環加上'if'。當然,還有更多不同的方法可以做到。 – Nequeq

0

您檢查當前的元素是從平均比以前更近,但如果它是有效地走近了,你不救的距離爲最小的一個,使用它接下來,您需要:

for(int i = 0; i<size; i++){ 
    double dist = Math.abs(array[i]-avg); 
    if(dist < record){ 
     answer = array[i]; 
     record = dist;   //<--- 
    } 
} 
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); 
    } 
    }