2015-01-07 45 views
1

是的,問題似乎相當容易。我被要求編寫一小段代碼(Java)來查找整數數組的替代元素的總和和平均值。起始位置將由用戶給出。例如,如果用戶輸入3作爲起始位置,則總和模塊將從索引(3-1 = 2)開始。我的目標是不完成我的作業或東西,但要了解我的代碼爲什麼不起作用。所以如果有人可以指出並建議修復?下面的代碼:整數陣列的替代元素的總和

import java.util.Scanner; 
public class Program { 

static int ar[]; static int sum = 0; static double avg = 0.0; 
static Scanner sc = new Scanner(System.in); 
public Program(int s){ 
    ar = new int[s]; 
} 
void accept(){ 
    for (int i = 0; i<ar.length; i++){ 
     System.out.println("Enter value of ar["+i+"] : "); 
     ar[i] = sc.nextInt(); 
    } 
} 
void calc(int pos){ 
    for (int i = (pos-1); i<ar.length; i+=2){ 
     sum = ar[i] + ar[i+1]; 
    } 
} 
public static void main(String[] args){ 
    boolean run = true; 
    while (run){ 
    System.out.println("Enter the size of the array: "); 
    int size = sc.nextInt(); 
    Program a = new Program(size); 
    a.accept(); 
    System.out.println("Enter starting position: "); int pos = sc.nextInt(); //Accept position 
    if (pos<0 || pos>ar.length){ 
     System.out.println("ERROR: Restart operations"); 
     run = true; 
    } 
    a.calc(pos); //Index = pos - 1; 
    run = false; avg = sum/ar.length; 
    System.out.println("The sum of alternate elements is: " + sum + "\n and their average is: " + avg); 

    } 
} 
} 

回答

0

在你calc方法,你得到for循環定義權(即初始值,條件和增量都是正確的),但在循環內,該sum計算是錯誤的。 ar[i] - - 在每次迭代中,你應該在當前的元素添加到總sum

for (int i = (pos-1); i<ar.length; i+=2){ 
    sum = sum + ar[i]; // or sum += ar[i]; 
} 

您還可以在平均計算的錯誤:

avg = sum/ar.length; 

這隻會是如果平均正確在所有元素上。由於平均數在一半以上,所以不應該除以ar.length

+0

謝謝!我添加了ar.length - pos,現在它工作。真誠的感謝。 –

+0

@MissionCoding ar.length-pos也是錯誤的,因爲你只求和pos-1和ar.length-1之間的一半元素 – Eran