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);
}
}
}
謝謝!我添加了ar.length - pos,現在它工作。真誠的感謝。 –
@MissionCoding ar.length-pos也是錯誤的,因爲你只求和pos-1和ar.length-1之間的一半元素 – Eran